From 43488d327412f8bd7b10d5ecb9526751131af6fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Wed, 19 Aug 2026 14:52:09 +0200 Subject: [PATCH 01/20] feat(appbar): reintroduction of subtitle --- example/src/Examples/AppbarExample.tsx | 6 +- src/components/Appbar/Appbar.tsx | 2 +- src/components/Appbar/AppbarContent.tsx | 80 ++++++++++++++----- src/components/Appbar/utils.ts | 15 +++- .../__tests__/Appbar/Appbar.test.tsx | 31 +++++++ .../Appbar/__snapshots__/Appbar.test.tsx.snap | 8 +- 6 files changed, 113 insertions(+), 29 deletions(-) diff --git a/example/src/Examples/AppbarExample.tsx b/example/src/Examples/AppbarExample.tsx index 2d4eb0bbc4..10f4b0bb92 100644 --- a/example/src/Examples/AppbarExample.tsx +++ b/example/src/Examples/AppbarExample.tsx @@ -52,7 +52,11 @@ const AppbarExample = () => { {showLeftIcon && ( navigation.goBack()} /> )} - setShowSnackbar(true)} /> + setShowSnackbar(true)} + /> {isCenterAlignedMode ? false : showCalendarIcon && ( diff --git a/src/components/Appbar/Appbar.tsx b/src/components/Appbar/Appbar.tsx index 8ef9965819..c42304765b 100644 --- a/src/components/Appbar/Appbar.tsx +++ b/src/components/Appbar/Appbar.tsx @@ -220,7 +220,7 @@ const Appbar = ({ { backgroundColor }, styles.appbar, { - height: modeAppbarHeight[mode], + minHeight: modeAppbarHeight[mode], }, insets, restStyle, diff --git a/src/components/Appbar/AppbarContent.tsx b/src/components/Appbar/AppbarContent.tsx index 5270aa271d..826477619d 100644 --- a/src/components/Appbar/AppbarContent.tsx +++ b/src/components/Appbar/AppbarContent.tsx @@ -8,8 +8,13 @@ import type { ViewProps, } from 'react-native'; -import { modeTextVariant } from './utils'; +import { + modeTextVariant, + modeSubtitleTextVariant, + modeSubtitleTextSpacing, +} from './utils'; import { useInternalTheme } from '../../core/theming'; +import type { TypescaleKey } from '../../theme/types'; import type { $RemoveChildren, ThemeProp } from '../../types'; import Text from '../Typography/Text'; import type { TextRef } from '../Typography/Text'; @@ -36,6 +41,14 @@ export type Props = $RemoveChildren & { * Reference for the title. */ titleRef?: React.RefObject; + /** + * Text or component for the subtitle. + */ + subtitle?: React.ReactNode; + /** + * Style for the subtitle. + */ + subtitleStyle?: StyleProp; /** * Function to execute on press. */ @@ -68,7 +81,7 @@ export type Props = $RemoveChildren & { } & (TitleString | TitleElement); /** - * A component used to display a title in an appbar. + * A component used to display a title and optional subtitle in an appbar. * * ## Usage * ```js @@ -77,7 +90,7 @@ export type Props = $RemoveChildren & { * * const MyComponent = () => ( * - * + * * * ); * @@ -86,6 +99,8 @@ export type Props = $RemoveChildren & { */ const AppbarContent = ({ color: titleColor, + subtitle, + subtitleStyle, onPress, disabled, style, @@ -110,7 +125,9 @@ const AppbarContent = ({ 'center-aligned': styles.v3DefaultContainer, }; - const variant = modeTextVariant[mode]; + const variant = modeTextVariant[mode] as TypescaleKey; + const subtitleVariant = modeSubtitleTextVariant[mode] as TypescaleKey; + const subtitleTopPadding = modeSubtitleTextSpacing[mode]; const contentWrapperProps = { pointerEvents: 'box-none', @@ -122,24 +139,43 @@ const AppbarContent = ({ const content = ( <> {typeof title === 'string' ? ( - - {title} - + <> + + {title} + + {subtitle ? ( + + {subtitle} + + ) : null} + ) : ( title )} diff --git a/src/components/Appbar/utils.ts b/src/components/Appbar/utils.ts index a6ea546b34..85c5eecc7a 100644 --- a/src/components/Appbar/utils.ts +++ b/src/components/Appbar/utils.ts @@ -86,7 +86,6 @@ type RenderAppbarContentProps = BaseProps & { theme?: ThemeProp; }; -export const DEFAULT_APPBAR_HEIGHT = 56; const MD3_DEFAULT_APPBAR_HEIGHT = 64; export const modeAppbarHeight = { @@ -103,6 +102,20 @@ export const modeTextVariant = { 'center-aligned': 'titleLarge', } as const; +export const modeSubtitleTextVariant = { + small: 'labelSmall', + medium: 'labelMedium', + large: 'labelLarge', + 'center-aligned': 'labelSmall', +} as const; + +export const modeSubtitleTextSpacing = { + small: undefined, + medium: 4, + large: 8, + 'center-aligned': undefined, +} as const satisfies Record; + export const filterAppbarActions = ( children: React.ReactNode, isLeading = false diff --git a/src/components/__tests__/Appbar/Appbar.test.tsx b/src/components/__tests__/Appbar/Appbar.test.tsx index 27cd573f9d..e18fc08671 100644 --- a/src/components/__tests__/Appbar/Appbar.test.tsx +++ b/src/components/__tests__/Appbar/Appbar.test.tsx @@ -277,6 +277,37 @@ describe('AppbarContent', () => { expect(screen.getByText('Title')).toBeOnTheScreen(); }); + + it('should render subtitle with MD3 typography and color tokens', async () => { + await render( + + + + ); + + expect(screen.getByTestId('appbar-content-subtitle-text')).toHaveStyle({ + ...getTheme().fonts.labelSmall, + color: getTheme().colors.onSurfaceVariant, + }); + }); + + it('should apply a custom subtitle style', async () => { + const customSubtitleColor = getTheme().colors.error; + + await render( + + + + ); + + expect(screen.getByTestId('appbar-content-subtitle-text')).toHaveStyle({ + color: customSubtitleColor, + }); + }); }); describe('getAppbarColors', () => { diff --git a/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap b/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap index a5d9d95766..59c778e4be 100644 --- a/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap +++ b/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap @@ -6,7 +6,6 @@ exports[`Appbar does not pass any additional props to Searchbar 1`] = ` style={ { "backgroundColor": "rgba(254, 247, 255, 1)", - "height": 64, "shadowColor": "rgba(0, 0, 0, 1)", "shadowOffset": { "height": 0, @@ -24,8 +23,9 @@ exports[`Appbar does not pass any additional props to Searchbar 1`] = ` { "alignItems": "center", "backgroundColor": "rgba(254, 247, 255, 1)", - "flex": 1, + "flex": undefined, "flexDirection": "row", + "minHeight": 64, "paddingBottom": undefined, "paddingHorizontal": 4, "paddingLeft": undefined, @@ -422,7 +422,6 @@ exports[`Appbar passes additional props to AppbarBackAction, AppbarContent and A style={ { "backgroundColor": "rgba(254, 247, 255, 1)", - "height": 64, "shadowColor": "rgba(0, 0, 0, 1)", "shadowOffset": { "height": 0, @@ -440,8 +439,9 @@ exports[`Appbar passes additional props to AppbarBackAction, AppbarContent and A { "alignItems": "center", "backgroundColor": "rgba(254, 247, 255, 1)", - "flex": 1, + "flex": undefined, "flexDirection": "row", + "minHeight": 64, "paddingBottom": undefined, "paddingHorizontal": 4, "paddingLeft": undefined, From 1b82ff5608a2ac513698f3e62e26c7c988d8d254 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Fri, 21 Aug 2026 11:10:28 +0200 Subject: [PATCH 02/20] feat(appbar): flat structure + expressive material design --- src/components/AppbarV3/Appbar.tsx | 200 ++++++++++++++++++++++ src/components/AppbarV3/AppbarAction.tsx | 70 ++++++++ src/components/AppbarV3/AppbarContent.tsx | 171 ++++++++++++++++++ src/components/AppbarV3/index.ts | 12 ++ src/components/AppbarV3/types.ts | 130 ++++++++++++++ src/components/AppbarV3/utils.ts | 29 ++++ src/index.tsx | 11 ++ 7 files changed, 623 insertions(+) create mode 100644 src/components/AppbarV3/Appbar.tsx create mode 100644 src/components/AppbarV3/AppbarAction.tsx create mode 100644 src/components/AppbarV3/AppbarContent.tsx create mode 100644 src/components/AppbarV3/index.ts create mode 100644 src/components/AppbarV3/types.ts create mode 100644 src/components/AppbarV3/utils.ts diff --git a/src/components/AppbarV3/Appbar.tsx b/src/components/AppbarV3/Appbar.tsx new file mode 100644 index 0000000000..b7d8070d8b --- /dev/null +++ b/src/components/AppbarV3/Appbar.tsx @@ -0,0 +1,200 @@ +import { StyleSheet, View } from 'react-native'; +import type { ColorValue, ViewStyle } from 'react-native'; + +import { useSafeAreaInsets } from 'react-native-safe-area-context'; + +import AppbarAction from './AppbarAction'; +import AppbarContent from './AppbarContent'; +import type { AppbarAction as AppbarActionConfig, Props } from './types'; +import { APPBAR_ACTION_SIZE, getActionsWidth, getAppbarHeight } from './utils'; +import { useInternalTheme } from '../../core/theming'; +import type { Theme } from '../../types'; +import { getAppbarBorders } from '../Appbar/utils'; +import Surface from '../Surface'; + +const Appbar = ({ + actions = [], + contentStyle, + isScrolled = false, + leadingAction, + onTitlePress, + safeAreaInsets, + statusBarHeight, + style, + subtitle, + subtitleColor, + subtitleMaxFontSizeMultiplier, + subtitleStyle, + testID = 'appbar', + theme: themeOverrides, + title, + titleAlignment = 'leading', + titleColor, + titleDisabled, + titleImage, + titleMaxFontSizeMultiplier, + titleRef, + titleStyle, + variant, + ref, + ...rest +}: Props) => { + const theme = useInternalTheme(themeOverrides) as Theme; + const detectedInsets = useSafeAreaInsets(); + const flattenedStyle = StyleSheet.flatten(style); + const { backgroundColor: customBackground, ...restStyle } = (flattenedStyle || + {}) as Exclude & { + backgroundColor?: ColorValue; + }; + const backgroundColor = + customBackground ?? + (isScrolled ? theme.colors.surfaceContainer : theme.colors.surface); + const resolvedTitleColor = titleColor ?? theme.colors.onSurface; + const resolvedSubtitleColor = subtitleColor ?? theme.colors.onSurfaceVariant; + const hasSubtitle = typeof subtitle === 'string' && subtitle.length > 0; + const minHeight = getAppbarHeight(variant, hasSubtitle); + const topInset = statusBarHeight ?? safeAreaInsets?.top ?? detectedInsets.top; + const leftInset = safeAreaInsets?.left ?? detectedInsets.left; + const rightInset = safeAreaInsets?.right ?? detectedInsets.right; + const horizontalInset = Math.max(leftInset, rightInset); + const borderRadius = getAppbarBorders(restStyle as ViewStyle); + const centered = titleAlignment === 'center'; + + const renderLeadingAction = () => + leadingAction ? ( + + ) : null; + + const renderActions = () => + actions.map((action, index) => ( + + )); + + const contentProps = { + alignment: titleAlignment, + contentStyle, + onTitlePress, + subtitle, + subtitleColor: resolvedSubtitleColor, + subtitleMaxFontSizeMultiplier, + subtitleStyle, + testID: `${testID}-content`, + theme, + title, + titleColor: resolvedTitleColor, + titleDisabled, + titleImage, + titleMaxFontSizeMultiplier, + titleRef, + titleStyle, + variant, + }; + + const renderSmallAppbar = () => { + if (centered) { + const sideWidth = Math.max( + leadingAction ? APPBAR_ACTION_SIZE : 0, + getActionsWidth(actions as readonly AppbarActionConfig[]) + ); + + return ( + + + {renderLeadingAction()} + + + + {renderActions()} + + + ); + } + + return ( + + {renderLeadingAction()} + + {renderActions()} + + ); + }; + + const renderFlexibleAppbar = () => ( + + + {renderLeadingAction()} + {renderActions()} + + + + ); + + return ( + + + {variant === 'small' ? renderSmallAppbar() : renderFlexibleAppbar()} + + + ); +}; + +const styles = StyleSheet.create({ + appbar: { + paddingHorizontal: 4, + }, + smallRow: { + flex: 1, + flexDirection: 'row', + alignItems: 'center', + }, + flexibleContainer: { + flex: 1, + }, + controlsRow: { + minHeight: 56, + flexDirection: 'row', + alignItems: 'flex-start', + justifyContent: 'space-between', + }, + trailingActions: { + flexDirection: 'row', + justifyContent: 'flex-end', + }, + side: { + flexDirection: 'row', + }, + titleLeading: { + marginStart: 12, + }, + titleWithLeading: { + marginStart: 4, + }, +}); + +export default Appbar; + +// @component-docs ignore-next-line +export { Appbar }; diff --git a/src/components/AppbarV3/AppbarAction.tsx b/src/components/AppbarV3/AppbarAction.tsx new file mode 100644 index 0000000000..b9eb1a2cca --- /dev/null +++ b/src/components/AppbarV3/AppbarAction.tsx @@ -0,0 +1,70 @@ +import { StyleSheet } from 'react-native'; + +import type { + AppbarAction as AppbarActionConfig, + AppbarLeadingAction, +} from './types'; +import type { Theme, ThemeProp } from '../../types'; +import AppbarBackIcon from '../Appbar/AppbarBackIcon'; +import IconButton from '../IconButton/IconButton'; + +type Props = { + action: AppbarActionConfig | AppbarLeadingAction; + leading?: boolean; + theme: ThemeProp; +}; + +const AppbarAction = ({ action, leading = false, theme }: Props) => { + const { + color, + key: _key, + style, + variant = 'standard', + width, + ...rest + } = action; + const { type: _type, ...buttonProps } = rest as typeof rest & { + type?: 'back' | 'icon'; + }; + const isBackAction = 'type' in action && action.type === 'back'; + const resolvedTheme = theme as Theme; + const mode = + variant === 'filled' + ? 'contained' + : variant === 'tonal' + ? 'contained-tonal' + : undefined; + + return ( + + ); +}; + +const styles = StyleSheet.create({ + action: { + margin: 4, + }, + wideAction: { + width: 56, + }, +}); + +export default AppbarAction; diff --git a/src/components/AppbarV3/AppbarContent.tsx b/src/components/AppbarV3/AppbarContent.tsx new file mode 100644 index 0000000000..67f98583b0 --- /dev/null +++ b/src/components/AppbarV3/AppbarContent.tsx @@ -0,0 +1,171 @@ +import { Pressable, StyleSheet, View } from 'react-native'; +import type { ColorValue, StyleProp, ViewStyle } from 'react-native'; + +import type { + AppbarTitleAlignment, + AppbarVariant, + Props as AppbarProps, +} from './types'; +import type { Theme, TypescaleKey } from '../../types'; +import Text from '../Typography/Text'; + +type Props = Pick< + AppbarProps, + | 'contentStyle' + | 'onTitlePress' + | 'subtitle' + | 'subtitleMaxFontSizeMultiplier' + | 'subtitleStyle' + | 'title' + | 'titleDisabled' + | 'titleImage' + | 'titleMaxFontSizeMultiplier' + | 'titleRef' + | 'titleStyle' +> & { + alignment: AppbarTitleAlignment; + subtitleColor: ColorValue; + theme: Theme; + titleColor: ColorValue; + variant: AppbarVariant; + style?: StyleProp; + testID: string; +}; + +const titleVariants = { + small: 'titleLarge', + 'medium-flexible': 'headlineMedium', + 'large-flexible': 'displaySmall', +} as const satisfies Record; + +const subtitleVariants = { + small: 'labelSmall', + 'medium-flexible': 'labelLarge', + 'large-flexible': 'titleMedium', +} as const satisfies Record; + +const subtitleSpacing = { + small: 0, + 'medium-flexible': 4, + 'large-flexible': 8, +} as const satisfies Record; + +const AppbarContent = ({ + alignment, + contentStyle, + onTitlePress, + subtitle, + subtitleColor, + subtitleMaxFontSizeMultiplier, + subtitleStyle, + testID, + theme, + title, + titleColor, + titleDisabled, + titleImage, + titleMaxFontSizeMultiplier, + titleRef, + titleStyle, + variant, + style, +}: Props) => { + const titleVariant = titleVariants[variant]; + const subtitleVariant = subtitleVariants[variant]; + const centered = alignment === 'center'; + + const content = titleImage ? ( + titleImage + ) : ( + <> + + {title} + + {subtitle ? ( + + {subtitle} + + ) : null} + + ); + + const wrapperProps = { + testID, + style: [ + styles.container, + variant !== 'small' && styles.flexibleContainer, + centered && styles.centeredContainer, + style, + contentStyle, + ], + }; + + if (onTitlePress) { + return ( + + {content} + + ); + } + + return {content}; +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: 'center', + minWidth: 0, + }, + flexibleContainer: { + flex: 0, + paddingHorizontal: 16, + paddingTop: 8, + paddingBottom: 12, + }, + centeredContainer: { + alignItems: 'center', + }, + text: { + alignSelf: 'stretch', + }, + centeredText: { + textAlign: 'center', + }, +}); + +export default AppbarContent; diff --git a/src/components/AppbarV3/index.ts b/src/components/AppbarV3/index.ts new file mode 100644 index 0000000000..7891d3b6a0 --- /dev/null +++ b/src/components/AppbarV3/index.ts @@ -0,0 +1,12 @@ +export { default } from './Appbar'; +export { Appbar } from './Appbar'; +export type { + AppbarAction, + AppbarActions, + AppbarFilledAction, + AppbarLeadingAction, + AppbarStandardAction, + AppbarTitleAlignment, + AppbarVariant, + Props, +} from './types'; diff --git a/src/components/AppbarV3/types.ts b/src/components/AppbarV3/types.ts new file mode 100644 index 0000000000..2f6e9874e7 --- /dev/null +++ b/src/components/AppbarV3/types.ts @@ -0,0 +1,130 @@ +import * as React from 'react'; +import type { + Animated, + ColorValue, + GestureResponderEvent, + StyleProp, + TextStyle, + View, + ViewProps, + ViewStyle, +} from 'react-native'; + +import type { ThemeProp } from '../../types'; +import type { IconSource } from '../Icon'; +import type { Props as IconButtonProps } from '../IconButton/IconButton'; +import type { TextRef } from '../Typography/Text'; + +export type AppbarVariant = 'small' | 'medium-flexible' | 'large-flexible'; + +export type AppbarTitleAlignment = 'leading' | 'center'; + +type AppbarActionBase = Omit< + IconButtonProps, + 'icon' | 'iconColor' | 'mode' | 'selected' | 'size' | 'theme' | 'aria-label' +> & { + /** Stable key used when rendering an action from the actions array. */ + key?: React.Key; + /** Icon displayed by the action. */ + icon: IconSource; + /** Accessible label announced for the icon button. */ + 'aria-label': string; + /** Custom action icon color. */ + color?: ColorValue; +}; + +export type AppbarStandardAction = AppbarActionBase & { + variant?: 'standard'; + width?: never; +}; + +export type AppbarFilledAction = AppbarActionBase & { + /** Filled primary and tonal actions use the corresponding IconButton colors. */ + variant: 'filled' | 'tonal'; + /** Expressive filled actions can use the default or wide container. */ + width?: 'default' | 'wide'; +}; + +export type AppbarAction = AppbarStandardAction | AppbarFilledAction; + +/** A filled action replaces the standard action group and is valid on its own. */ +export type AppbarActions = + | readonly AppbarStandardAction[] + | readonly [AppbarFilledAction]; + +type AppbarLeadingIconAction = AppbarStandardAction & { + type?: 'icon'; +}; + +type AppbarBackAction = Omit< + AppbarStandardAction, + 'aria-label' | 'icon' | 'type' +> & { + /** Uses the platform-aware Paper back icon. */ + type: 'back'; + icon?: never; + 'aria-label'?: string; +}; + +export type AppbarLeadingAction = AppbarLeadingIconAction | AppbarBackAction; + +type AppbarTextTitle = { + /** Written headline displayed by the app bar. */ + title: string; + titleImage?: never; + /** Optional supporting text displayed below the headline. */ + subtitle?: string; + titleStyle?: StyleProp; + subtitleStyle?: StyleProp; + titleRef?: React.RefObject; + titleMaxFontSizeMultiplier?: number; + subtitleMaxFontSizeMultiplier?: number; +}; + +type AppbarImageTitle = { + title?: never; + /** Image or logo which replaces the written headline. */ + titleImage: React.ReactElement; + subtitle?: never; + titleStyle?: never; + subtitleStyle?: never; + titleRef?: never; + titleMaxFontSizeMultiplier?: never; + subtitleMaxFontSizeMultiplier?: never; +}; + +type AppbarBaseProps = Omit & { + /** Expressive app bar size variant. */ + variant: AppbarVariant; + /** Headline and subtitle alignment. */ + titleAlignment?: AppbarTitleAlignment; + /** Optional leading navigation action. */ + leadingAction?: AppbarLeadingAction; + /** Trailing icon actions. */ + actions?: AppbarActions; + /** Uses the on-scroll container color when true. */ + isScrolled?: boolean; + /** Override for the automatic top safe-area inset. */ + statusBarHeight?: number; + /** Safe-area inset overrides. Unspecified values use the detected insets. */ + safeAreaInsets?: { + top?: number; + left?: number; + right?: number; + }; + /** Called when the title area is pressed. */ + onTitlePress?: (event: GestureResponderEvent) => void; + /** Disables title-area interaction. */ + titleDisabled?: boolean; + /** Custom headline color. */ + titleColor?: ColorValue; + /** Custom subtitle color. */ + subtitleColor?: ColorValue; + /** Style applied to the title area. */ + contentStyle?: StyleProp; + style?: Animated.WithAnimatedValue>; + ref?: React.Ref; + theme?: ThemeProp; +}; + +export type Props = AppbarBaseProps & (AppbarTextTitle | AppbarImageTitle); diff --git a/src/components/AppbarV3/utils.ts b/src/components/AppbarV3/utils.ts new file mode 100644 index 0000000000..b8ac83ab64 --- /dev/null +++ b/src/components/AppbarV3/utils.ts @@ -0,0 +1,29 @@ +import type { AppbarAction, AppbarVariant } from './types'; + +export const APPBAR_ACTION_SIZE = 48; +export const APPBAR_WIDE_ACTION_SIZE = 64; + +export const getAppbarHeight = ( + variant: AppbarVariant, + hasSubtitle: boolean +) => { + if (variant === 'small') { + return 64; + } + + if (variant === 'medium-flexible') { + return hasSubtitle ? 136 : 112; + } + + return hasSubtitle ? 152 : 120; +}; + +export const getActionsWidth = (actions: readonly AppbarAction[]) => + actions.reduce( + (width, action) => + width + + (action.variant !== 'standard' && action.width === 'wide' + ? APPBAR_WIDE_ACTION_SIZE + : APPBAR_ACTION_SIZE), + 0 + ); diff --git a/src/index.tsx b/src/index.tsx index 8863e2fa20..7469301a7b 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -45,6 +45,7 @@ export { default as Snackbar } from './components/Snackbar'; export { default as Surface } from './components/Surface'; export { default as Switch } from './components/Switch/Switch'; export { default as Appbar } from './components/Appbar'; +export { default as AppbarV3 } from './components/AppbarV3'; export { default as TouchableRipple } from './components/TouchableRipple/TouchableRipple'; export { default as TextInput } from './components/TextInput'; export { default as ToggleButton } from './components/ToggleButton'; @@ -60,6 +61,16 @@ export type { Props as AppbarActionProps } from './components/Appbar/AppbarActio export type { Props as AppbarBackActionProps } from './components/Appbar/AppbarBackAction'; export type { Props as AppbarContentProps } from './components/Appbar/AppbarContent'; export type { Props as AppbarHeaderProps } from './components/Appbar/AppbarHeader'; +export type { + Props as AppbarV3Props, + AppbarAction as AppbarV3Action, + AppbarActions as AppbarV3Actions, + AppbarFilledAction as AppbarV3FilledAction, + AppbarLeadingAction as AppbarV3LeadingAction, + AppbarStandardAction as AppbarV3StandardAction, + AppbarTitleAlignment as AppbarV3TitleAlignment, + AppbarVariant as AppbarV3Variant, +} from './components/AppbarV3'; export type { Props as AvatarIconProps } from './components/Avatar/AvatarIcon'; export type { Props as AvatarImageProps } from './components/Avatar/AvatarImage'; export type { Props as AvatarTextProps } from './components/Avatar/AvatarText'; From 025005d9b4aba92f72a2bac65688e264136f70a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Fri, 21 Aug 2026 11:10:57 +0200 Subject: [PATCH 03/20] feat(example): example app update --- example/src/ExampleList.tsx | 2 + example/src/Examples/AppbarV3Example.tsx | 269 +++++++++++++++++++++++ 2 files changed, 271 insertions(+) create mode 100644 example/src/Examples/AppbarV3Example.tsx diff --git a/example/src/ExampleList.tsx b/example/src/ExampleList.tsx index 8a2646d798..bd30b8feb6 100644 --- a/example/src/ExampleList.tsx +++ b/example/src/ExampleList.tsx @@ -6,6 +6,7 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context'; import ActivityIndicatorExample from './Examples/ActivityIndicatorExample'; import AppbarExample from './Examples/AppbarExample'; +import AppbarV3Example from './Examples/AppbarV3Example'; import AvatarExample from './Examples/AvatarExample'; import BadgeExample from './Examples/BadgeExample'; import BannerExample from './Examples/BannerExample'; @@ -51,6 +52,7 @@ import TouchableRippleExample from './Examples/TouchableRippleExample'; export const mainExamples = { ActivityIndicator: ActivityIndicatorExample, Appbar: AppbarExample, + AppbarV3: AppbarV3Example, Avatar: AvatarExample, Badge: BadgeExample, Banner: BannerExample, diff --git a/example/src/Examples/AppbarV3Example.tsx b/example/src/Examples/AppbarV3Example.tsx new file mode 100644 index 0000000000..3e4a8fe1c8 --- /dev/null +++ b/example/src/Examples/AppbarV3Example.tsx @@ -0,0 +1,269 @@ +import * as React from 'react'; +import { Platform, StyleSheet, View } from 'react-native'; + +import { useNavigation } from '@react-navigation/native'; +import { + AppbarV3, + FAB, + IconButton, + List, + Palette, + RadioButton, + Snackbar, + Surface, + Switch, + Text, + useTheme, +} from 'react-native-paper'; +import type { + AppbarV3StandardAction, + AppbarV3TitleAlignment, + AppbarV3Variant, +} from 'react-native-paper'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; + +import ScreenWrapper from '../ScreenWrapper'; + +type AppbarConfiguration = AppbarV3Variant | 'small-centered'; + +const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical'; +const BOTTOM_APPBAR_HEIGHT = 80; +const MEDIUM_FAB_HEIGHT = 56; + +const AppbarV3Example = () => { + const navigation = useNavigation('AppbarV3'); + + const [showLeftIcon, setShowLeftIcon] = React.useState(true); + const [showSubtitle, setShowSubtitle] = React.useState(true); + const [showSearchIcon, setShowSearchIcon] = React.useState(true); + const [showMoreIcon, setShowMoreIcon] = React.useState(true); + const [showCustomColor, setShowCustomColor] = React.useState(false); + const [appbarConfiguration, setAppbarConfiguration] = + React.useState('small'); + const [showCalendarIcon, setShowCalendarIcon] = React.useState(false); + const [showScrolled, setShowScrolled] = React.useState(false); + const [showSnackbar, setShowSnackbar] = React.useState(false); + + const theme = useTheme(); + const { bottom, left, right } = useSafeAreaInsets(); + const isCentered = appbarConfiguration === 'small-centered'; + const variant: AppbarV3Variant = isCentered ? 'small' : appbarConfiguration; + const titleAlignment: AppbarV3TitleAlignment = isCentered + ? 'center' + : 'leading'; + + React.useLayoutEffect(() => { + const actions: AppbarV3StandardAction[] = []; + + if (!isCentered && showCalendarIcon) { + actions.push({ + icon: 'calendar', + 'aria-label': 'Calendar', + onPress: () => {}, + }); + } + + if (showSearchIcon) { + actions.push({ + icon: 'magnify', + 'aria-label': 'Search', + onPress: () => {}, + }); + } + + if (showMoreIcon) { + actions.push({ + icon: MORE_ICON, + 'aria-label': 'More options', + onPress: () => {}, + }); + } + + navigation.setOptions({ + header: () => ( + setShowSnackbar(true)} + isScrolled={showScrolled} + leadingAction={ + showLeftIcon + ? { + type: 'back', + onPress: () => navigation.goBack(), + } + : undefined + } + actions={actions} + /> + ), + }); + }, [ + isCentered, + navigation, + showCalendarIcon, + showCustomColor, + showLeftIcon, + showMoreIcon, + showScrolled, + showSearchIcon, + showSubtitle, + titleAlignment, + variant, + ]); + + const renderFAB = () => ( + {}} + style={[ + styles.fab, + { + right: 16 + right, + top: (BOTTOM_APPBAR_HEIGHT - MEDIUM_FAB_HEIGHT) / 2, + }, + ]} + /> + ); + + const renderDefaultOptions = () => ( + <> + + Left icon + + + + Subtitle + + + + Search icon + + + + More icon + + + + Calendar icon + + + + Custom Color + + + + Scrolled + + + + ); + + return ( + <> + + + {renderDefaultOptions()} + + + + setAppbarConfiguration(value as AppbarConfiguration) + } + > + + Small (default) + + + + Medium flexible + + + + Large flexible + + + + Small (centered) + + + + + + + + {}} /> + {}} /> + {}} /> + {}} /> + + {renderFAB()} + + setShowSnackbar(false)} + duration={Snackbar.DURATION_SHORT} + > + Heading pressed + + + ); +}; + +AppbarV3Example.title = 'Appbar V3'; + +export default AppbarV3Example; + +const styles = StyleSheet.create({ + contentContainer: { + paddingVertical: 8, + }, + row: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + paddingVertical: 8, + paddingHorizontal: 16, + }, + bottom: { + position: 'absolute', + left: 0, + right: 0, + bottom: 0, + }, + bottomActions: { + height: BOTTOM_APPBAR_HEIGHT, + flexDirection: 'row', + alignItems: 'center', + paddingHorizontal: 4, + }, + fab: { + position: 'absolute', + }, + customColor: { + backgroundColor: Palette.secondary80, + }, +}); From d2cbdc48fd6701d9d2b4c2918772265138fd1fce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Fri, 21 Aug 2026 11:23:55 +0200 Subject: [PATCH 04/20] feat(example): handling scrolling behavior --- example/src/Examples/AppbarV3Example.tsx | 42 +++++++++++++++++++----- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/example/src/Examples/AppbarV3Example.tsx b/example/src/Examples/AppbarV3Example.tsx index 3e4a8fe1c8..ba488ddef2 100644 --- a/example/src/Examples/AppbarV3Example.tsx +++ b/example/src/Examples/AppbarV3Example.tsx @@ -1,5 +1,6 @@ import * as React from 'react'; -import { Platform, StyleSheet, View } from 'react-native'; +import { Platform, StyleSheet, useWindowDimensions, View } from 'react-native'; +import type { NativeScrollEvent, NativeSyntheticEvent } from 'react-native'; import { useNavigation } from '@react-navigation/native'; import { @@ -41,11 +42,12 @@ const AppbarV3Example = () => { const [appbarConfiguration, setAppbarConfiguration] = React.useState('small'); const [showCalendarIcon, setShowCalendarIcon] = React.useState(false); - const [showScrolled, setShowScrolled] = React.useState(false); + const [isScrolled, setIsScrolled] = React.useState(false); const [showSnackbar, setShowSnackbar] = React.useState(false); const theme = useTheme(); const { bottom, left, right } = useSafeAreaInsets(); + const { height: windowHeight } = useWindowDimensions(); const isCentered = appbarConfiguration === 'small-centered'; const variant: AppbarV3Variant = isCentered ? 'small' : appbarConfiguration; const titleAlignment: AppbarV3TitleAlignment = isCentered @@ -88,7 +90,7 @@ const AppbarV3Example = () => { title="Title" subtitle={showSubtitle ? 'Subtitle' : undefined} onTitlePress={() => setShowSnackbar(true)} - isScrolled={showScrolled} + isScrolled={isScrolled} leadingAction={ showLeftIcon ? { @@ -108,13 +110,26 @@ const AppbarV3Example = () => { showCustomColor, showLeftIcon, showMoreIcon, - showScrolled, + isScrolled, showSearchIcon, showSubtitle, titleAlignment, variant, ]); + const handleScroll = React.useCallback( + ({ nativeEvent }: NativeSyntheticEvent) => { + const nextIsScrolled = nativeEvent.contentOffset.y > 1; + + setIsScrolled((currentIsScrolled) => + currentIsScrolled === nextIsScrolled + ? currentIsScrolled + : nextIsScrolled + ); + }, + [] + ); + const renderFAB = () => ( { Custom Color - - Scrolled - - ); @@ -170,8 +181,21 @@ const AppbarV3Example = () => { <> + + + {renderDefaultOptions()} From 8a34d7c2011da55de429170513c38ad0cc50f658 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Fri, 21 Aug 2026 11:34:49 +0200 Subject: [PATCH 05/20] fix(appbar): unnecessary animations on actions change --- example/src/Examples/AppbarV3Example.tsx | 3 +++ src/components/AppbarV3/Appbar.tsx | 8 ++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/example/src/Examples/AppbarV3Example.tsx b/example/src/Examples/AppbarV3Example.tsx index ba488ddef2..526e511090 100644 --- a/example/src/Examples/AppbarV3Example.tsx +++ b/example/src/Examples/AppbarV3Example.tsx @@ -59,6 +59,7 @@ const AppbarV3Example = () => { if (!isCentered && showCalendarIcon) { actions.push({ + key: 'calendar', icon: 'calendar', 'aria-label': 'Calendar', onPress: () => {}, @@ -67,6 +68,7 @@ const AppbarV3Example = () => { if (showSearchIcon) { actions.push({ + key: 'search', icon: 'magnify', 'aria-label': 'Search', onPress: () => {}, @@ -75,6 +77,7 @@ const AppbarV3Example = () => { if (showMoreIcon) { actions.push({ + key: 'more', icon: MORE_ICON, 'aria-label': 'More options', onPress: () => {}, diff --git a/src/components/AppbarV3/Appbar.tsx b/src/components/AppbarV3/Appbar.tsx index b7d8070d8b..03db31c423 100644 --- a/src/components/AppbarV3/Appbar.tsx +++ b/src/components/AppbarV3/Appbar.tsx @@ -66,8 +66,12 @@ const Appbar = ({ ) : null; const renderActions = () => - actions.map((action, index) => ( - + actions.map((action) => ( + )); const contentProps = { From 5a188f779fb40b2a85ba119d8efb03803cdfa1e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Fri, 21 Aug 2026 13:20:33 +0200 Subject: [PATCH 06/20] feat(appbar): filled icon button support --- example/src/Examples/AppbarV3Example.tsx | 89 +++++++++++++++++++++--- src/components/AppbarV3/AppbarAction.tsx | 14 ++-- 2 files changed, 89 insertions(+), 14 deletions(-) diff --git a/example/src/Examples/AppbarV3Example.tsx b/example/src/Examples/AppbarV3Example.tsx index 526e511090..8f3ed5b48d 100644 --- a/example/src/Examples/AppbarV3Example.tsx +++ b/example/src/Examples/AppbarV3Example.tsx @@ -17,6 +17,8 @@ import { useTheme, } from 'react-native-paper'; import type { + AppbarV3Actions, + AppbarV3FilledAction, AppbarV3StandardAction, AppbarV3TitleAlignment, AppbarV3Variant, @@ -26,6 +28,8 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context'; import ScreenWrapper from '../ScreenWrapper'; type AppbarConfiguration = AppbarV3Variant | 'small-centered'; +type FilledActionVariant = AppbarV3FilledAction['variant']; +type FilledActionWidth = NonNullable; const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical'; const BOTTOM_APPBAR_HEIGHT = 80; @@ -42,6 +46,11 @@ const AppbarV3Example = () => { const [appbarConfiguration, setAppbarConfiguration] = React.useState('small'); const [showCalendarIcon, setShowCalendarIcon] = React.useState(false); + const [showFilledAction, setShowFilledAction] = React.useState(false); + const [filledActionVariant, setFilledActionVariant] = + React.useState('filled'); + const [filledActionWidth, setFilledActionWidth] = + React.useState('default'); const [isScrolled, setIsScrolled] = React.useState(false); const [showSnackbar, setShowSnackbar] = React.useState(false); @@ -55,10 +64,10 @@ const AppbarV3Example = () => { : 'leading'; React.useLayoutEffect(() => { - const actions: AppbarV3StandardAction[] = []; + const standardActions: AppbarV3StandardAction[] = []; if (!isCentered && showCalendarIcon) { - actions.push({ + standardActions.push({ key: 'calendar', icon: 'calendar', 'aria-label': 'Calendar', @@ -67,7 +76,7 @@ const AppbarV3Example = () => { } if (showSearchIcon) { - actions.push({ + standardActions.push({ key: 'search', icon: 'magnify', 'aria-label': 'Search', @@ -76,7 +85,7 @@ const AppbarV3Example = () => { } if (showMoreIcon) { - actions.push({ + standardActions.push({ key: 'more', icon: MORE_ICON, 'aria-label': 'More options', @@ -84,13 +93,26 @@ const AppbarV3Example = () => { }); } + const actions: AppbarV3Actions = showFilledAction + ? [ + { + key: 'share', + icon: 'share-variant', + 'aria-label': 'Share', + variant: filledActionVariant, + width: filledActionWidth, + onPress: () => {}, + }, + ] + : standardActions; + navigation.setOptions({ header: () => ( setShowSnackbar(true)} isScrolled={isScrolled} @@ -108,9 +130,12 @@ const AppbarV3Example = () => { }); }, [ isCentered, + filledActionVariant, + filledActionWidth, navigation, showCalendarIcon, showCustomColor, + showFilledAction, showLeftIcon, showMoreIcon, isScrolled, @@ -157,19 +182,31 @@ const AppbarV3Example = () => { Subtitle + + Filled trailing action + + Search icon - + More icon - + Calendar icon @@ -202,6 +239,42 @@ const AppbarV3Example = () => { {renderDefaultOptions()} + {showFilledAction ? ( + + Style + + setFilledActionVariant(value as FilledActionVariant) + } + > + + Primary filled + + + + Tonal filled + + + + Width + + setFilledActionWidth(value as FilledActionWidth) + } + > + + Default + + + + Wide + + + + + ) : null} { : variant === 'tonal' ? 'contained-tonal' : undefined; + const iconColor = + color ?? + (mode + ? undefined + : leading + ? resolvedTheme.colors.onSurface + : resolvedTheme.colors.onSurfaceVariant); return ( { aria-label={ isBackAction ? (action['aria-label'] ?? 'Back') : action['aria-label'] } - iconColor={ - color ?? - (leading - ? resolvedTheme.colors.onSurface - : resolvedTheme.colors.onSurfaceVariant) - } + iconColor={iconColor} mode={mode} selected={mode ? true : undefined} size={24} From c2b5f60fe63923f6071459523900e15e6baff65d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Mon, 24 Aug 2026 08:32:32 +0200 Subject: [PATCH 07/20] feat(appbar): showcase title centering in example app --- example/src/Examples/AppbarV3Example.tsx | 55 +++++++++++++----------- 1 file changed, 31 insertions(+), 24 deletions(-) diff --git a/example/src/Examples/AppbarV3Example.tsx b/example/src/Examples/AppbarV3Example.tsx index 8f3ed5b48d..0cfc4fa753 100644 --- a/example/src/Examples/AppbarV3Example.tsx +++ b/example/src/Examples/AppbarV3Example.tsx @@ -27,7 +27,6 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context'; import ScreenWrapper from '../ScreenWrapper'; -type AppbarConfiguration = AppbarV3Variant | 'small-centered'; type FilledActionVariant = AppbarV3FilledAction['variant']; type FilledActionWidth = NonNullable; @@ -44,7 +43,8 @@ const AppbarV3Example = () => { const [showMoreIcon, setShowMoreIcon] = React.useState(true); const [showCustomColor, setShowCustomColor] = React.useState(false); const [appbarConfiguration, setAppbarConfiguration] = - React.useState('small'); + React.useState('small'); + const [isTitleCentered, setIsTitleCentered] = React.useState(false); const [showCalendarIcon, setShowCalendarIcon] = React.useState(false); const [showFilledAction, setShowFilledAction] = React.useState(false); const [filledActionVariant, setFilledActionVariant] = @@ -57,16 +57,14 @@ const AppbarV3Example = () => { const theme = useTheme(); const { bottom, left, right } = useSafeAreaInsets(); const { height: windowHeight } = useWindowDimensions(); - const isCentered = appbarConfiguration === 'small-centered'; - const variant: AppbarV3Variant = isCentered ? 'small' : appbarConfiguration; - const titleAlignment: AppbarV3TitleAlignment = isCentered + const titleAlignment: AppbarV3TitleAlignment = isTitleCentered ? 'center' : 'leading'; React.useLayoutEffect(() => { const standardActions: AppbarV3StandardAction[] = []; - if (!isCentered && showCalendarIcon) { + if (showCalendarIcon) { standardActions.push({ key: 'calendar', icon: 'calendar', @@ -110,7 +108,7 @@ const AppbarV3Example = () => { header: () => ( { ), }); }, [ - isCentered, + appbarConfiguration, filledActionVariant, filledActionWidth, navigation, @@ -142,7 +140,6 @@ const AppbarV3Example = () => { showSearchIcon, showSubtitle, titleAlignment, - variant, ]); const handleScroll = React.useCallback( @@ -182,6 +179,10 @@ const AppbarV3Example = () => { Subtitle + + Center title and subtitle + + Filled trailing action @@ -205,8 +206,8 @@ const AppbarV3Example = () => { Calendar icon @@ -244,9 +245,11 @@ const AppbarV3Example = () => { Style - setFilledActionVariant(value as FilledActionVariant) - } + onValueChange={(value: string) => { + if (value === 'filled' || value === 'tonal') { + setFilledActionVariant(value); + } + }} > Primary filled @@ -260,9 +263,11 @@ const AppbarV3Example = () => { Width - setFilledActionWidth(value as FilledActionWidth) - } + onValueChange={(value: string) => { + if (value === 'default' || value === 'wide') { + setFilledActionWidth(value); + } + }} > Default @@ -278,9 +283,15 @@ const AppbarV3Example = () => { - setAppbarConfiguration(value as AppbarConfiguration) - } + onValueChange={(value: string) => { + if ( + value === 'small' || + value === 'medium-flexible' || + value === 'large-flexible' + ) { + setAppbarConfiguration(value); + } + }} > Small (default) @@ -294,10 +305,6 @@ const AppbarV3Example = () => { Large flexible - - Small (centered) - - From 9be328786927830e7684f9617c5a3a6d5fc20962 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Mon, 24 Aug 2026 11:19:54 +0200 Subject: [PATCH 08/20] feat(appbar): title image support --- example/src/Examples/AppbarV3Example.tsx | 109 +++++++++++++++++----- src/components/AppbarV3/Appbar.tsx | 90 ++++++++++++++---- src/components/AppbarV3/AppbarContent.tsx | 34 ++++++- src/components/AppbarV3/types.ts | 29 ++++-- src/components/AppbarV3/utils.ts | 1 + 5 files changed, 211 insertions(+), 52 deletions(-) diff --git a/example/src/Examples/AppbarV3Example.tsx b/example/src/Examples/AppbarV3Example.tsx index 0cfc4fa753..2337ed6b61 100644 --- a/example/src/Examples/AppbarV3Example.tsx +++ b/example/src/Examples/AppbarV3Example.tsx @@ -1,5 +1,11 @@ import * as React from 'react'; -import { Platform, StyleSheet, useWindowDimensions, View } from 'react-native'; +import { + Image, + Platform, + StyleSheet, + useWindowDimensions, + View, +} from 'react-native'; import type { NativeScrollEvent, NativeSyntheticEvent } from 'react-native'; import { useNavigation } from '@react-navigation/native'; @@ -39,6 +45,7 @@ const AppbarV3Example = () => { const [showLeftIcon, setShowLeftIcon] = React.useState(true); const [showSubtitle, setShowSubtitle] = React.useState(true); + const [showTitleImage, setShowTitleImage] = React.useState(false); const [showSearchIcon, setShowSearchIcon] = React.useState(true); const [showMoreIcon, setShowMoreIcon] = React.useState(true); const [showCustomColor, setShowCustomColor] = React.useState(false); @@ -104,27 +111,72 @@ const AppbarV3Example = () => { ] : standardActions; + const leadingAction = showLeftIcon + ? { + type: 'back' as const, + onPress: () => navigation.goBack(), + } + : undefined; + const titleImage = ( + + ); + const commonProps = { + actions, + isScrolled, + leadingAction, + onTitlePress: () => setShowSnackbar(true), + style: showCustomColor ? styles.customColor : null, + titleAlignment, + }; + navigation.setOptions({ - header: () => ( - setShowSnackbar(true)} - isScrolled={isScrolled} - leadingAction={ - showLeftIcon - ? { - type: 'back', - onPress: () => navigation.goBack(), - } - : undefined - } - actions={actions} - /> - ), + header: () => { + if (appbarConfiguration === 'small') { + return showTitleImage ? ( + + ) : ( + + ); + } + + return showTitleImage ? ( + + ) : ( + + ); + }, }); }, [ appbarConfiguration, @@ -139,6 +191,7 @@ const AppbarV3Example = () => { isScrolled, showSearchIcon, showSubtitle, + showTitleImage, titleAlignment, ]); @@ -177,7 +230,15 @@ const AppbarV3Example = () => { Subtitle - + + + + Title image + Center title and subtitle @@ -373,4 +434,8 @@ const styles = StyleSheet.create({ customColor: { backgroundColor: Palette.secondary80, }, + titleImage: { + width: 32, + height: 32, + }, }); diff --git a/src/components/AppbarV3/Appbar.tsx b/src/components/AppbarV3/Appbar.tsx index 03db31c423..a4bbc7473c 100644 --- a/src/components/AppbarV3/Appbar.tsx +++ b/src/components/AppbarV3/Appbar.tsx @@ -1,14 +1,18 @@ import { StyleSheet, View } from 'react-native'; -import type { ColorValue, ViewStyle } from 'react-native'; +import type { ColorValue } from 'react-native'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import AppbarAction from './AppbarAction'; import AppbarContent from './AppbarContent'; -import type { AppbarAction as AppbarActionConfig, Props } from './types'; -import { APPBAR_ACTION_SIZE, getActionsWidth, getAppbarHeight } from './utils'; +import type { Props } from './types'; +import { + APPBAR_ACTION_SIZE, + APPBAR_TITLE_IMAGE_HEIGHT, + getActionsWidth, + getAppbarHeight, +} from './utils'; import { useInternalTheme } from '../../core/theming'; -import type { Theme } from '../../types'; import { getAppbarBorders } from '../Appbar/utils'; import Surface from '../Surface'; @@ -39,13 +43,17 @@ const Appbar = ({ ref, ...rest }: Props) => { - const theme = useInternalTheme(themeOverrides) as Theme; + const theme = useInternalTheme(themeOverrides); const detectedInsets = useSafeAreaInsets(); const flattenedStyle = StyleSheet.flatten(style); - const { backgroundColor: customBackground, ...restStyle } = (flattenedStyle || - {}) as Exclude & { + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + const resolvedStyle = (flattenedStyle || {}) as Exclude< + typeof flattenedStyle, + number + > & { backgroundColor?: ColorValue; }; + const { backgroundColor: customBackground, ...restStyle } = resolvedStyle; const backgroundColor = customBackground ?? (isScrolled ? theme.colors.surfaceContainer : theme.colors.surface); @@ -57,7 +65,7 @@ const Appbar = ({ const leftInset = safeAreaInsets?.left ?? detectedInsets.left; const rightInset = safeAreaInsets?.right ?? detectedInsets.right; const horizontalInset = Math.max(leftInset, rightInset); - const borderRadius = getAppbarBorders(restStyle as ViewStyle); + const borderRadius = getAppbarBorders(restStyle); const centered = titleAlignment === 'center'; const renderLeadingAction = () => @@ -94,11 +102,23 @@ const Appbar = ({ variant, }; + const renderFlexibleTitleImage = () => + titleImage ? ( + + {titleImage} + + ) : null; + const renderSmallAppbar = () => { - if (centered) { + if (centered || titleImage) { const sideWidth = Math.max( leadingAction ? APPBAR_ACTION_SIZE : 0, - getActionsWidth(actions as readonly AppbarActionConfig[]) + getActionsWidth(actions) ); return ( @@ -128,15 +148,40 @@ const Appbar = ({ ); }; - const renderFlexibleAppbar = () => ( - - - {renderLeadingAction()} - {renderActions()} + const renderFlexibleAppbar = () => { + const sideWidth = Math.max( + leadingAction ? APPBAR_ACTION_SIZE : 0, + getActionsWidth(actions) + ); + + return ( + + {titleImage ? ( + + + {renderLeadingAction()} + + {renderFlexibleTitleImage()} + + {renderActions()} + + + ) : ( + + {renderLeadingAction()} + {renderActions()} + + )} + - - - ); + ); + }; return ( ; const subtitleVariants = { - small: 'labelSmall', + small: 'labelMedium', 'medium-flexible': 'labelLarge', 'large-flexible': 'titleMedium', } as const satisfies Record; @@ -73,9 +74,17 @@ const AppbarContent = ({ const titleVariant = titleVariants[variant]; const subtitleVariant = subtitleVariants[variant]; const centered = alignment === 'center'; + const hasTitleImage = variant === 'small' && Boolean(titleImage); - const content = titleImage ? ( - titleImage + const content = hasTitleImage ? ( + + {titleImage} + ) : ( <> {content}; + return ( + + {content} + + ); }; const styles = StyleSheet.create({ @@ -166,6 +185,13 @@ const styles = StyleSheet.create({ centeredText: { textAlign: 'center', }, + titleImage: { + height: APPBAR_TITLE_IMAGE_HEIGHT, + maxWidth: '100%', + alignItems: 'center', + justifyContent: 'center', + overflow: 'hidden', + }, }); export default AppbarContent; diff --git a/src/components/AppbarV3/types.ts b/src/components/AppbarV3/types.ts index 2f6e9874e7..9fbc0eb3c8 100644 --- a/src/components/AppbarV3/types.ts +++ b/src/components/AppbarV3/types.ts @@ -68,10 +68,9 @@ type AppbarBackAction = Omit< export type AppbarLeadingAction = AppbarLeadingIconAction | AppbarBackAction; -type AppbarTextTitle = { +type AppbarWrittenTitle = { /** Written headline displayed by the app bar. */ title: string; - titleImage?: never; /** Optional supporting text displayed below the headline. */ subtitle?: string; titleStyle?: StyleProp; @@ -81,10 +80,20 @@ type AppbarTextTitle = { subtitleMaxFontSizeMultiplier?: number; }; -type AppbarImageTitle = { - title?: never; - /** Image or logo which replaces the written headline. */ +type AppbarTitleImage = { + /** Image or logo displayed in the app bar. It should fit within 32dp height. */ titleImage: React.ReactElement; +}; + +type AppbarTextTitle = AppbarWrittenTitle & { + variant: AppbarVariant; + titleImage?: never; +}; + +type AppbarSmallImageTitle = AppbarTitleImage & { + variant: 'small'; + /** Accessible page title. The image replaces this text visually. */ + title: string; subtitle?: never; titleStyle?: never; subtitleStyle?: never; @@ -93,9 +102,12 @@ type AppbarImageTitle = { subtitleMaxFontSizeMultiplier?: never; }; +type AppbarFlexibleImageTitle = AppbarWrittenTitle & + AppbarTitleImage & { + variant: Exclude; + }; + type AppbarBaseProps = Omit & { - /** Expressive app bar size variant. */ - variant: AppbarVariant; /** Headline and subtitle alignment. */ titleAlignment?: AppbarTitleAlignment; /** Optional leading navigation action. */ @@ -127,4 +139,5 @@ type AppbarBaseProps = Omit & { theme?: ThemeProp; }; -export type Props = AppbarBaseProps & (AppbarTextTitle | AppbarImageTitle); +export type Props = AppbarBaseProps & + (AppbarTextTitle | AppbarSmallImageTitle | AppbarFlexibleImageTitle); diff --git a/src/components/AppbarV3/utils.ts b/src/components/AppbarV3/utils.ts index b8ac83ab64..43f2478039 100644 --- a/src/components/AppbarV3/utils.ts +++ b/src/components/AppbarV3/utils.ts @@ -2,6 +2,7 @@ import type { AppbarAction, AppbarVariant } from './types'; export const APPBAR_ACTION_SIZE = 48; export const APPBAR_WIDE_ACTION_SIZE = 64; +export const APPBAR_TITLE_IMAGE_HEIGHT = 32; export const getAppbarHeight = ( variant: AppbarVariant, From 91c870bcfe7829da2b4c648b6d0ba64c41e7ca03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Mon, 24 Aug 2026 13:18:13 +0200 Subject: [PATCH 09/20] feat(appbar): initial search bar support --- example/src/Examples/AppbarV3Example.tsx | 76 +++++++++++- src/components/AppbarV3/Appbar.tsx | 141 +++++++++++++++++++--- src/components/AppbarV3/AppbarContent.tsx | 10 +- src/components/AppbarV3/index.ts | 1 + src/components/AppbarV3/types.ts | 67 ++++++++-- src/components/AppbarV3/utils.ts | 8 +- src/index.tsx | 1 + 7 files changed, 261 insertions(+), 43 deletions(-) diff --git a/example/src/Examples/AppbarV3Example.tsx b/example/src/Examples/AppbarV3Example.tsx index 2337ed6b61..5d18a207a8 100644 --- a/example/src/Examples/AppbarV3Example.tsx +++ b/example/src/Examples/AppbarV3Example.tsx @@ -25,6 +25,7 @@ import { import type { AppbarV3Actions, AppbarV3FilledAction, + AppbarV3LeadingAction, AppbarV3StandardAction, AppbarV3TitleAlignment, AppbarV3Variant, @@ -40,6 +41,38 @@ const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical'; const BOTTOM_APPBAR_HEIGHT = 80; const MEDIUM_FAB_HEIGHT = 56; +type SearchAppbarHeaderProps = { + actions: AppbarV3StandardAction[]; + isScrolled: boolean; + leadingAction?: AppbarV3LeadingAction; + showCustomColor: boolean; +}; + +const SearchAppbarHeader = ({ + actions, + isScrolled, + leadingAction, + showCustomColor, +}: SearchAppbarHeaderProps) => { + const [searchQuery, setSearchQuery] = React.useState(''); + + return ( + + ); +}; + const AppbarV3Example = () => { const navigation = useNavigation('AppbarV3'); @@ -80,7 +113,7 @@ const AppbarV3Example = () => { }); } - if (showSearchIcon) { + if (showSearchIcon && appbarConfiguration !== 'search') { standardActions.push({ key: 'search', icon: 'magnify', @@ -136,6 +169,17 @@ const AppbarV3Example = () => { navigation.setOptions({ header: () => { + if (appbarConfiguration === 'search') { + return ( + + ); + } + if (appbarConfiguration === 'small') { return showTitleImage ? ( { Subtitle Title image - + Center title and subtitle - + Filled trailing action - + Search icon @@ -347,6 +406,7 @@ const AppbarV3Example = () => { onValueChange={(value: string) => { if ( value === 'small' || + value === 'search' || value === 'medium-flexible' || value === 'large-flexible' ) { @@ -354,6 +414,10 @@ const AppbarV3Example = () => { } }} > + + Search + + Small (default) diff --git a/src/components/AppbarV3/Appbar.tsx b/src/components/AppbarV3/Appbar.tsx index a4bbc7473c..595bcf9b7b 100644 --- a/src/components/AppbarV3/Appbar.tsx +++ b/src/components/AppbarV3/Appbar.tsx @@ -1,5 +1,6 @@ +import * as React from 'react'; import { StyleSheet, View } from 'react-native'; -import type { ColorValue } from 'react-native'; +import type { ColorValue, LayoutChangeEvent } from 'react-native'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; @@ -11,9 +12,11 @@ import { APPBAR_TITLE_IMAGE_HEIGHT, getActionsWidth, getAppbarHeight, + getAppbarSearchWidth, } from './utils'; import { useInternalTheme } from '../../core/theming'; import { getAppbarBorders } from '../Appbar/utils'; +import Searchbar from '../Searchbar'; import Surface from '../Surface'; const Appbar = ({ @@ -23,6 +26,7 @@ const Appbar = ({ leadingAction, onTitlePress, safeAreaInsets, + searchBar, statusBarHeight, style, subtitle, @@ -45,6 +49,7 @@ const Appbar = ({ }: Props) => { const theme = useInternalTheme(themeOverrides); const detectedInsets = useSafeAreaInsets(); + const [searchSlotWidth, setSearchSlotWidth] = React.useState(0); const flattenedStyle = StyleSheet.flatten(style); // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion const resolvedStyle = (flattenedStyle || {}) as Exclude< @@ -68,6 +73,17 @@ const Appbar = ({ const borderRadius = getAppbarBorders(restStyle); const centered = titleAlignment === 'center'; + const handleSearchSlotLayout = React.useCallback( + ({ nativeEvent }: LayoutChangeEvent) => { + const nextWidth = nativeEvent.layout.width; + + setSearchSlotWidth((currentWidth) => + currentWidth === nextWidth ? currentWidth : nextWidth + ); + }, + [] + ); + const renderLeadingAction = () => leadingAction ? ( @@ -82,26 +98,83 @@ const Appbar = ({ /> )); - const contentProps = { - alignment: titleAlignment, - contentStyle, - onTitlePress, - subtitle, - subtitleColor: resolvedSubtitleColor, - subtitleMaxFontSizeMultiplier, - subtitleStyle, - testID: `${testID}-content`, - theme, - title, - titleColor: resolvedTitleColor, - titleDisabled, - titleImage, - titleMaxFontSizeMultiplier, - titleRef, - titleStyle, - variant, + const renderSearchAppbar = () => { + if (!searchBar) { + return null; + } + + const { + inputStyle: searchInputStyle, + style: searchStyle, + testID: searchTestID = `${testID}-search`, + ...searchProps + } = searchBar; + const searchWidth = searchSlotWidth + ? getAppbarSearchWidth(searchSlotWidth) + : '100%'; + const searchBackgroundColor = isScrolled + ? theme.colors.surfaceContainerHighest + : theme.colors.surfaceContainer; + + return ( + + {renderLeadingAction()} + + + + {renderActions()} + + ); }; + const contentProps = + variant !== 'search' + ? { + alignment: titleAlignment, + contentStyle, + onTitlePress, + subtitle, + subtitleColor: resolvedSubtitleColor, + subtitleMaxFontSizeMultiplier, + subtitleStyle, + testID: `${testID}-content`, + theme, + title, + titleColor: resolvedTitleColor, + titleDisabled, + titleImage, + titleMaxFontSizeMultiplier, + titleRef, + titleStyle, + variant, + } + : null; + const renderFlexibleTitleImage = () => titleImage ? ( { + if (!contentProps) { + return null; + } + if (centered || titleImage) { const sideWidth = Math.max( leadingAction ? APPBAR_ACTION_SIZE : 0, @@ -149,6 +226,10 @@ const Appbar = ({ }; const renderFlexibleAppbar = () => { + if (!contentProps) { + return null; + } + const sideWidth = Math.max( leadingAction ? APPBAR_ACTION_SIZE : 0, getActionsWidth(actions) @@ -204,7 +285,11 @@ const Appbar = ({ testID={testID} style={[styles.appbar, { backgroundColor, minHeight }, restStyle]} > - {variant === 'small' ? renderSmallAppbar() : renderFlexibleAppbar()} + {variant === 'search' + ? renderSearchAppbar() + : variant === 'small' + ? renderSmallAppbar() + : renderFlexibleAppbar()} ); @@ -219,6 +304,22 @@ const styles = StyleSheet.create({ flexDirection: 'row', alignItems: 'center', }, + searchRow: { + flex: 1, + flexDirection: 'row', + alignItems: 'center', + }, + searchSlot: { + flex: 1, + marginHorizontal: 8, + alignItems: 'center', + }, + searchBar: { + maxWidth: '100%', + }, + searchInput: { + textAlign: 'center', + }, flexibleContainer: { flex: 1, }, diff --git a/src/components/AppbarV3/AppbarContent.tsx b/src/components/AppbarV3/AppbarContent.tsx index 27bcab24d4..e09e6b507d 100644 --- a/src/components/AppbarV3/AppbarContent.tsx +++ b/src/components/AppbarV3/AppbarContent.tsx @@ -3,7 +3,7 @@ import type { ColorValue, StyleProp, ViewStyle } from 'react-native'; import type { AppbarTitleAlignment, - AppbarVariant, + AppbarTitleVariant, Props as AppbarProps, } from './types'; import { APPBAR_TITLE_IMAGE_HEIGHT } from './utils'; @@ -28,7 +28,7 @@ type Props = Pick< subtitleColor: ColorValue; theme: Theme; titleColor: ColorValue; - variant: AppbarVariant; + variant: AppbarTitleVariant; style?: StyleProp; testID: string; }; @@ -37,19 +37,19 @@ const titleVariants = { small: 'titleLarge', 'medium-flexible': 'headlineMedium', 'large-flexible': 'displaySmall', -} as const satisfies Record; +} as const satisfies Record; const subtitleVariants = { small: 'labelMedium', 'medium-flexible': 'labelLarge', 'large-flexible': 'titleMedium', -} as const satisfies Record; +} as const satisfies Record; const subtitleSpacing = { small: 0, 'medium-flexible': 4, 'large-flexible': 8, -} as const satisfies Record; +} as const satisfies Record; const AppbarContent = ({ alignment, diff --git a/src/components/AppbarV3/index.ts b/src/components/AppbarV3/index.ts index 7891d3b6a0..9bed0afff1 100644 --- a/src/components/AppbarV3/index.ts +++ b/src/components/AppbarV3/index.ts @@ -5,6 +5,7 @@ export type { AppbarActions, AppbarFilledAction, AppbarLeadingAction, + AppbarSearchbarProps, AppbarStandardAction, AppbarTitleAlignment, AppbarVariant, diff --git a/src/components/AppbarV3/types.ts b/src/components/AppbarV3/types.ts index 9fbc0eb3c8..00dedd1a60 100644 --- a/src/components/AppbarV3/types.ts +++ b/src/components/AppbarV3/types.ts @@ -13,9 +13,16 @@ import type { import type { ThemeProp } from '../../types'; import type { IconSource } from '../Icon'; import type { Props as IconButtonProps } from '../IconButton/IconButton'; +import type { Props as SearchbarProps } from '../Searchbar'; import type { TextRef } from '../Typography/Text'; -export type AppbarVariant = 'small' | 'medium-flexible' | 'large-flexible'; +export type AppbarVariant = + | 'search' + | 'small' + | 'medium-flexible' + | 'large-flexible'; + +export type AppbarTitleVariant = Exclude; export type AppbarTitleAlignment = 'leading' | 'center'; @@ -86,7 +93,7 @@ type AppbarTitleImage = { }; type AppbarTextTitle = AppbarWrittenTitle & { - variant: AppbarVariant; + variant: AppbarTitleVariant; titleImage?: never; }; @@ -104,16 +111,12 @@ type AppbarSmallImageTitle = AppbarTitleImage & { type AppbarFlexibleImageTitle = AppbarWrittenTitle & AppbarTitleImage & { - variant: Exclude; + variant: Exclude; }; type AppbarBaseProps = Omit & { - /** Headline and subtitle alignment. */ - titleAlignment?: AppbarTitleAlignment; /** Optional leading navigation action. */ leadingAction?: AppbarLeadingAction; - /** Trailing icon actions. */ - actions?: AppbarActions; /** Uses the on-scroll container color when true. */ isScrolled?: boolean; /** Override for the automatic top safe-area inset. */ @@ -124,6 +127,16 @@ type AppbarBaseProps = Omit & { left?: number; right?: number; }; + style?: Animated.WithAnimatedValue>; + ref?: React.Ref; + theme?: ThemeProp; +}; + +type AppbarTitleProps = { + /** Headline and subtitle alignment. */ + titleAlignment?: AppbarTitleAlignment; + /** Trailing icon actions. */ + actions?: AppbarActions; /** Called when the title area is pressed. */ onTitlePress?: (event: GestureResponderEvent) => void; /** Disables title-area interaction. */ @@ -134,10 +147,42 @@ type AppbarBaseProps = Omit & { subtitleColor?: ColorValue; /** Style applied to the title area. */ contentStyle?: StyleProp; - style?: Animated.WithAnimatedValue>; - ref?: React.Ref; - theme?: ThemeProp; + searchBar?: never; +}; + +export type AppbarSearchbarProps = Omit< + SearchbarProps, + 'elevation' | 'mode' | 'showDivider' | 'theme' +> & { + /** Search hint. Material guidance recommends including the word “Search”. */ + placeholder: string; +}; + +type AppbarSearchProps = { + variant: 'search'; + /** Props forwarded to the existing Paper Searchbar. */ + searchBar: AppbarSearchbarProps; + /** Exterior trailing icon actions. */ + actions?: readonly AppbarStandardAction[]; + title?: never; + subtitle?: never; + titleImage?: never; + titleAlignment?: never; + titleStyle?: never; + subtitleStyle?: never; + titleRef?: never; + titleMaxFontSizeMultiplier?: never; + subtitleMaxFontSizeMultiplier?: never; + onTitlePress?: never; + titleDisabled?: never; + titleColor?: never; + subtitleColor?: never; + contentStyle?: never; }; export type Props = AppbarBaseProps & - (AppbarTextTitle | AppbarSmallImageTitle | AppbarFlexibleImageTitle); + ( + | (AppbarTitleProps & + (AppbarTextTitle | AppbarSmallImageTitle | AppbarFlexibleImageTitle)) + | AppbarSearchProps + ); diff --git a/src/components/AppbarV3/utils.ts b/src/components/AppbarV3/utils.ts index 43f2478039..2df8aa37bd 100644 --- a/src/components/AppbarV3/utils.ts +++ b/src/components/AppbarV3/utils.ts @@ -3,12 +3,18 @@ import type { AppbarAction, AppbarVariant } from './types'; export const APPBAR_ACTION_SIZE = 48; export const APPBAR_WIDE_ACTION_SIZE = 64; export const APPBAR_TITLE_IMAGE_HEIGHT = 32; +export const APPBAR_SEARCH_WIDTH_BREAKPOINT = 312; + +export const getAppbarSearchWidth = (availableWidth: number) => + availableWidth > APPBAR_SEARCH_WIDTH_BREAKPOINT + ? Math.max(APPBAR_SEARCH_WIDTH_BREAKPOINT, availableWidth / 2) + : availableWidth; export const getAppbarHeight = ( variant: AppbarVariant, hasSubtitle: boolean ) => { - if (variant === 'small') { + if (variant === 'search' || variant === 'small') { return 64; } diff --git a/src/index.tsx b/src/index.tsx index 7469301a7b..36a5eac3c9 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -67,6 +67,7 @@ export type { AppbarActions as AppbarV3Actions, AppbarFilledAction as AppbarV3FilledAction, AppbarLeadingAction as AppbarV3LeadingAction, + AppbarSearchbarProps as AppbarV3SearchbarProps, AppbarStandardAction as AppbarV3StandardAction, AppbarTitleAlignment as AppbarV3TitleAlignment, AppbarVariant as AppbarV3Variant, From 033024d9f74b3a42fae406d6e1c17cbc5a5040b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Mon, 24 Aug 2026 13:59:10 +0200 Subject: [PATCH 10/20] refactor(appbar): drop titleDisabled --- src/components/AppbarV3/Appbar.tsx | 2 -- src/components/AppbarV3/AppbarContent.tsx | 4 ---- src/components/AppbarV3/types.ts | 3 --- 3 files changed, 9 deletions(-) diff --git a/src/components/AppbarV3/Appbar.tsx b/src/components/AppbarV3/Appbar.tsx index 595bcf9b7b..f2933aa920 100644 --- a/src/components/AppbarV3/Appbar.tsx +++ b/src/components/AppbarV3/Appbar.tsx @@ -38,7 +38,6 @@ const Appbar = ({ title, titleAlignment = 'leading', titleColor, - titleDisabled, titleImage, titleMaxFontSizeMultiplier, titleRef, @@ -166,7 +165,6 @@ const Appbar = ({ theme, title, titleColor: resolvedTitleColor, - titleDisabled, titleImage, titleMaxFontSizeMultiplier, titleRef, diff --git a/src/components/AppbarV3/AppbarContent.tsx b/src/components/AppbarV3/AppbarContent.tsx index e09e6b507d..6be4305324 100644 --- a/src/components/AppbarV3/AppbarContent.tsx +++ b/src/components/AppbarV3/AppbarContent.tsx @@ -18,7 +18,6 @@ type Props = Pick< | 'subtitleMaxFontSizeMultiplier' | 'subtitleStyle' | 'title' - | 'titleDisabled' | 'titleImage' | 'titleMaxFontSizeMultiplier' | 'titleRef' @@ -63,7 +62,6 @@ const AppbarContent = ({ theme, title, titleColor, - titleDisabled, titleImage, titleMaxFontSizeMultiplier, titleRef, @@ -143,8 +141,6 @@ const AppbarContent = ({ {...wrapperProps} role="button" accessibilityLabel={hasTitleImage ? title : undefined} - aria-disabled={titleDisabled} - disabled={titleDisabled} onPress={onTitlePress} > {content} diff --git a/src/components/AppbarV3/types.ts b/src/components/AppbarV3/types.ts index 00dedd1a60..575f89cd7f 100644 --- a/src/components/AppbarV3/types.ts +++ b/src/components/AppbarV3/types.ts @@ -139,8 +139,6 @@ type AppbarTitleProps = { actions?: AppbarActions; /** Called when the title area is pressed. */ onTitlePress?: (event: GestureResponderEvent) => void; - /** Disables title-area interaction. */ - titleDisabled?: boolean; /** Custom headline color. */ titleColor?: ColorValue; /** Custom subtitle color. */ @@ -174,7 +172,6 @@ type AppbarSearchProps = { titleMaxFontSizeMultiplier?: never; subtitleMaxFontSizeMultiplier?: never; onTitlePress?: never; - titleDisabled?: never; titleColor?: never; subtitleColor?: never; contentStyle?: never; From ca9c2f65a9b2246e2339bbee158857abffbfa619 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Mon, 24 Aug 2026 14:27:44 +0200 Subject: [PATCH 11/20] feat(appbar): streamline props --- src/components/AppbarV3/Appbar.tsx | 20 +++-------- src/components/AppbarV3/AppbarContent.tsx | 34 +++++++------------ src/components/AppbarV3/index.ts | 2 ++ src/components/AppbarV3/types.ts | 41 +++++++++++------------ src/index.tsx | 2 ++ 5 files changed, 40 insertions(+), 59 deletions(-) diff --git a/src/components/AppbarV3/Appbar.tsx b/src/components/AppbarV3/Appbar.tsx index f2933aa920..e5351f909a 100644 --- a/src/components/AppbarV3/Appbar.tsx +++ b/src/components/AppbarV3/Appbar.tsx @@ -30,18 +30,13 @@ const Appbar = ({ statusBarHeight, style, subtitle, - subtitleColor, - subtitleMaxFontSizeMultiplier, - subtitleStyle, + subtitleProps, testID = 'appbar', theme: themeOverrides, title, titleAlignment = 'leading', - titleColor, titleImage, - titleMaxFontSizeMultiplier, - titleRef, - titleStyle, + titleProps, variant, ref, ...rest @@ -61,8 +56,6 @@ const Appbar = ({ const backgroundColor = customBackground ?? (isScrolled ? theme.colors.surfaceContainer : theme.colors.surface); - const resolvedTitleColor = titleColor ?? theme.colors.onSurface; - const resolvedSubtitleColor = subtitleColor ?? theme.colors.onSurfaceVariant; const hasSubtitle = typeof subtitle === 'string' && subtitle.length > 0; const minHeight = getAppbarHeight(variant, hasSubtitle); const topInset = statusBarHeight ?? safeAreaInsets?.top ?? detectedInsets.top; @@ -158,17 +151,12 @@ const Appbar = ({ contentStyle, onTitlePress, subtitle, - subtitleColor: resolvedSubtitleColor, - subtitleMaxFontSizeMultiplier, - subtitleStyle, + subtitleProps, testID: `${testID}-content`, theme, title, - titleColor: resolvedTitleColor, titleImage, - titleMaxFontSizeMultiplier, - titleRef, - titleStyle, + titleProps, variant, } : null; diff --git a/src/components/AppbarV3/AppbarContent.tsx b/src/components/AppbarV3/AppbarContent.tsx index 6be4305324..a24a5df401 100644 --- a/src/components/AppbarV3/AppbarContent.tsx +++ b/src/components/AppbarV3/AppbarContent.tsx @@ -1,5 +1,5 @@ import { Pressable, StyleSheet, View } from 'react-native'; -import type { ColorValue, StyleProp, ViewStyle } from 'react-native'; +import type { StyleProp, ViewStyle } from 'react-native'; import type { AppbarTitleAlignment, @@ -15,18 +15,13 @@ type Props = Pick< | 'contentStyle' | 'onTitlePress' | 'subtitle' - | 'subtitleMaxFontSizeMultiplier' - | 'subtitleStyle' + | 'subtitleProps' | 'title' | 'titleImage' - | 'titleMaxFontSizeMultiplier' - | 'titleRef' - | 'titleStyle' + | 'titleProps' > & { alignment: AppbarTitleAlignment; - subtitleColor: ColorValue; theme: Theme; - titleColor: ColorValue; variant: AppbarTitleVariant; style?: StyleProp; testID: string; @@ -55,17 +50,12 @@ const AppbarContent = ({ contentStyle, onTitlePress, subtitle, - subtitleColor, - subtitleMaxFontSizeMultiplier, - subtitleStyle, + subtitleProps, testID, theme, title, - titleColor, titleImage, - titleMaxFontSizeMultiplier, - titleRef, - titleStyle, + titleProps, variant, style, }: Props) => { @@ -86,19 +76,19 @@ const AppbarContent = ({ ) : ( <> {title} @@ -108,14 +98,14 @@ const AppbarContent = ({ variant={subtitleVariant} theme={theme} numberOfLines={1} - maxFontSizeMultiplier={subtitleMaxFontSizeMultiplier} + maxFontSizeMultiplier={subtitleProps?.maxFontSizeMultiplier} testID={`${testID}-subtitle-text`} style={[ styles.text, centered && styles.centeredText, { marginTop: subtitleSpacing[variant] }, - { color: subtitleColor }, - subtitleStyle, + { color: theme.colors.onSurfaceVariant }, + subtitleProps?.style, ]} > {subtitle} diff --git a/src/components/AppbarV3/index.ts b/src/components/AppbarV3/index.ts index 9bed0afff1..06fb7c8533 100644 --- a/src/components/AppbarV3/index.ts +++ b/src/components/AppbarV3/index.ts @@ -7,7 +7,9 @@ export type { AppbarLeadingAction, AppbarSearchbarProps, AppbarStandardAction, + AppbarTextProps, AppbarTitleAlignment, + AppbarTitleTextProps, AppbarVariant, Props, } from './types'; diff --git a/src/components/AppbarV3/types.ts b/src/components/AppbarV3/types.ts index 575f89cd7f..6f945f8156 100644 --- a/src/components/AppbarV3/types.ts +++ b/src/components/AppbarV3/types.ts @@ -26,6 +26,18 @@ export type AppbarTitleVariant = Exclude; export type AppbarTitleAlignment = 'leading' | 'center'; +export type AppbarTextProps = { + /** Style applied to the text. */ + style?: StyleProp; + /** Specifies the largest possible scale the font can reach. */ + maxFontSizeMultiplier?: number; +}; + +export type AppbarTitleTextProps = AppbarTextProps & { + /** Reference for the title heading. */ + ref?: React.RefObject; +}; + type AppbarActionBase = Omit< IconButtonProps, 'icon' | 'iconColor' | 'mode' | 'selected' | 'size' | 'theme' | 'aria-label' @@ -80,11 +92,10 @@ type AppbarWrittenTitle = { title: string; /** Optional supporting text displayed below the headline. */ subtitle?: string; - titleStyle?: StyleProp; - subtitleStyle?: StyleProp; - titleRef?: React.RefObject; - titleMaxFontSizeMultiplier?: number; - subtitleMaxFontSizeMultiplier?: number; + /** Props applied to the title heading. */ + titleProps?: AppbarTitleTextProps; + /** Props applied to the subtitle text. */ + subtitleProps?: AppbarTextProps; }; type AppbarTitleImage = { @@ -102,11 +113,8 @@ type AppbarSmallImageTitle = AppbarTitleImage & { /** Accessible page title. The image replaces this text visually. */ title: string; subtitle?: never; - titleStyle?: never; - subtitleStyle?: never; - titleRef?: never; - titleMaxFontSizeMultiplier?: never; - subtitleMaxFontSizeMultiplier?: never; + titleProps?: never; + subtitleProps?: never; }; type AppbarFlexibleImageTitle = AppbarWrittenTitle & @@ -139,10 +147,6 @@ type AppbarTitleProps = { actions?: AppbarActions; /** Called when the title area is pressed. */ onTitlePress?: (event: GestureResponderEvent) => void; - /** Custom headline color. */ - titleColor?: ColorValue; - /** Custom subtitle color. */ - subtitleColor?: ColorValue; /** Style applied to the title area. */ contentStyle?: StyleProp; searchBar?: never; @@ -166,14 +170,9 @@ type AppbarSearchProps = { subtitle?: never; titleImage?: never; titleAlignment?: never; - titleStyle?: never; - subtitleStyle?: never; - titleRef?: never; - titleMaxFontSizeMultiplier?: never; - subtitleMaxFontSizeMultiplier?: never; + titleProps?: never; + subtitleProps?: never; onTitlePress?: never; - titleColor?: never; - subtitleColor?: never; contentStyle?: never; }; diff --git a/src/index.tsx b/src/index.tsx index 36a5eac3c9..1726a497ec 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -69,7 +69,9 @@ export type { AppbarLeadingAction as AppbarV3LeadingAction, AppbarSearchbarProps as AppbarV3SearchbarProps, AppbarStandardAction as AppbarV3StandardAction, + AppbarTextProps as AppbarV3TextProps, AppbarTitleAlignment as AppbarV3TitleAlignment, + AppbarTitleTextProps as AppbarV3TitleTextProps, AppbarVariant as AppbarV3Variant, } from './components/AppbarV3'; export type { Props as AvatarIconProps } from './components/Avatar/AvatarIcon'; From 996b71671a37fdfc699c8529cb0bcef22f750ac0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Mon, 24 Aug 2026 14:44:09 +0200 Subject: [PATCH 12/20] refactor(appbar): search width adjustments --- src/components/AppbarV3/utils.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/components/AppbarV3/utils.ts b/src/components/AppbarV3/utils.ts index 2df8aa37bd..219f0d6cca 100644 --- a/src/components/AppbarV3/utils.ts +++ b/src/components/AppbarV3/utils.ts @@ -3,12 +3,16 @@ import type { AppbarAction, AppbarVariant } from './types'; export const APPBAR_ACTION_SIZE = 48; export const APPBAR_WIDE_ACTION_SIZE = 64; export const APPBAR_TITLE_IMAGE_HEIGHT = 32; -export const APPBAR_SEARCH_WIDTH_BREAKPOINT = 312; +export const APPBAR_SEARCH_MIN_WIDTH = 360; +export const APPBAR_SEARCH_MAX_WIDTH = 720; -export const getAppbarSearchWidth = (availableWidth: number) => - availableWidth > APPBAR_SEARCH_WIDTH_BREAKPOINT - ? Math.max(APPBAR_SEARCH_WIDTH_BREAKPOINT, availableWidth / 2) - : availableWidth; +export const getAppbarSearchWidth = (availableWidth: number) => { + if (availableWidth < APPBAR_SEARCH_MIN_WIDTH) { + return availableWidth; + } + + return Math.min(availableWidth, APPBAR_SEARCH_MAX_WIDTH); +}; export const getAppbarHeight = ( variant: AppbarVariant, From a1b0a4debbd55842f0da488377da3ad05f49853d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Tue, 25 Aug 2026 08:19:10 +0200 Subject: [PATCH 13/20] feat(appbar): adjust v3 example --- example/src/Examples/AppbarV3Example.tsx | 61 +----------------------- 1 file changed, 2 insertions(+), 59 deletions(-) diff --git a/example/src/Examples/AppbarV3Example.tsx b/example/src/Examples/AppbarV3Example.tsx index 5d18a207a8..c3734b6712 100644 --- a/example/src/Examples/AppbarV3Example.tsx +++ b/example/src/Examples/AppbarV3Example.tsx @@ -11,16 +11,12 @@ import type { NativeScrollEvent, NativeSyntheticEvent } from 'react-native'; import { useNavigation } from '@react-navigation/native'; import { AppbarV3, - FAB, - IconButton, List, Palette, RadioButton, Snackbar, - Surface, Switch, Text, - useTheme, } from 'react-native-paper'; import type { AppbarV3Actions, @@ -38,8 +34,6 @@ type FilledActionVariant = AppbarV3FilledAction['variant']; type FilledActionWidth = NonNullable; const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical'; -const BOTTOM_APPBAR_HEIGHT = 80; -const MEDIUM_FAB_HEIGHT = 56; type SearchAppbarHeaderProps = { actions: AppbarV3StandardAction[]; @@ -94,8 +88,7 @@ const AppbarV3Example = () => { const [isScrolled, setIsScrolled] = React.useState(false); const [showSnackbar, setShowSnackbar] = React.useState(false); - const theme = useTheme(); - const { bottom, left, right } = useSafeAreaInsets(); + const { bottom } = useSafeAreaInsets(); const { height: windowHeight } = useWindowDimensions(); const titleAlignment: AppbarV3TitleAlignment = isTitleCentered ? 'center' @@ -252,20 +245,6 @@ const AppbarV3Example = () => { [] ); - const renderFAB = () => ( - {}} - style={[ - styles.fab, - { - right: 16 + right, - top: (BOTTOM_APPBAR_HEIGHT - MEDIUM_FAB_HEIGHT) / 2, - }, - ]} - /> - ); - const renderDefaultOptions = () => ( <> @@ -341,7 +320,7 @@ const AppbarV3Example = () => { return ( <> { - - - {}} /> - {}} /> - {}} /> - {}} /> - - {renderFAB()} - setShowSnackbar(false)} @@ -480,21 +438,6 @@ const styles = StyleSheet.create({ paddingVertical: 8, paddingHorizontal: 16, }, - bottom: { - position: 'absolute', - left: 0, - right: 0, - bottom: 0, - }, - bottomActions: { - height: BOTTOM_APPBAR_HEIGHT, - flexDirection: 'row', - alignItems: 'center', - paddingHorizontal: 4, - }, - fab: { - position: 'absolute', - }, customColor: { backgroundColor: Palette.secondary80, }, From 64cd517e8e362f3656bbac7bcc0ef3c98721a9ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Tue, 25 Aug 2026 08:29:00 +0200 Subject: [PATCH 14/20] refactor(appbar): remove code smells --- src/components/AppbarV3/AppbarAction.tsx | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/components/AppbarV3/AppbarAction.tsx b/src/components/AppbarV3/AppbarAction.tsx index 974aa395ed..6889d45948 100644 --- a/src/components/AppbarV3/AppbarAction.tsx +++ b/src/components/AppbarV3/AppbarAction.tsx @@ -4,14 +4,14 @@ import type { AppbarAction as AppbarActionConfig, AppbarLeadingAction, } from './types'; -import type { Theme, ThemeProp } from '../../types'; +import type { Theme } from '../../types'; import AppbarBackIcon from '../Appbar/AppbarBackIcon'; import IconButton from '../IconButton/IconButton'; type Props = { action: AppbarActionConfig | AppbarLeadingAction; leading?: boolean; - theme: ThemeProp; + theme: Theme; }; const AppbarAction = ({ action, leading = false, theme }: Props) => { @@ -27,7 +27,6 @@ const AppbarAction = ({ action, leading = false, theme }: Props) => { type?: 'back' | 'icon'; }; const isBackAction = 'type' in action && action.type === 'back'; - const resolvedTheme = theme as Theme; const mode = variant === 'filled' ? 'contained' @@ -39,13 +38,13 @@ const AppbarAction = ({ action, leading = false, theme }: Props) => { (mode ? undefined : leading - ? resolvedTheme.colors.onSurface - : resolvedTheme.colors.onSurfaceVariant); + ? theme.colors.onSurface + : theme.colors.onSurfaceVariant); return ( Date: Tue, 25 Aug 2026 09:20:35 +0200 Subject: [PATCH 15/20] feat(appbar): accessibility related adjustments --- src/components/AppbarV3/Appbar.tsx | 20 +++++--- src/components/AppbarV3/AppbarContent.tsx | 22 ++++++++- src/components/AppbarV3/index.ts | 1 + src/components/AppbarV3/types.ts | 56 ++++++++++++++++++++--- src/index.tsx | 1 + 5 files changed, 84 insertions(+), 16 deletions(-) diff --git a/src/components/AppbarV3/Appbar.tsx b/src/components/AppbarV3/Appbar.tsx index e5351f909a..69a208ee30 100644 --- a/src/components/AppbarV3/Appbar.tsx +++ b/src/components/AppbarV3/Appbar.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; import { StyleSheet, View } from 'react-native'; -import type { ColorValue, LayoutChangeEvent } from 'react-native'; +import type { ColorValue, LayoutChangeEvent, ViewProps } from 'react-native'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; @@ -34,6 +34,7 @@ const Appbar = ({ testID = 'appbar', theme: themeOverrides, title, + titleActionProps, titleAlignment = 'leading', titleImage, titleProps, @@ -64,6 +65,14 @@ const Appbar = ({ const horizontalInset = Math.max(leftInset, rightInset); const borderRadius = getAppbarBorders(restStyle); const centered = titleAlignment === 'center'; + const { + accessibilityLabel: _accessibilityLabel, + accessibilityRole: _accessibilityRole, + accessible: _accessible, + 'aria-label': _ariaLabel, + role: _role, + ...viewProps + } = rest as ViewProps; const handleSearchSlotLayout = React.useCallback( ({ nativeEvent }: LayoutChangeEvent) => { @@ -83,11 +92,7 @@ const Appbar = ({ const renderActions = () => actions.map((action) => ( - + )); const renderSearchAppbar = () => { @@ -155,6 +160,7 @@ const Appbar = ({ testID: `${testID}-content`, theme, title, + titleActionProps, titleImage, titleProps, variant, @@ -267,7 +273,7 @@ const Appbar = ({ ]} > diff --git a/src/components/AppbarV3/AppbarContent.tsx b/src/components/AppbarV3/AppbarContent.tsx index a24a5df401..a1118a63c4 100644 --- a/src/components/AppbarV3/AppbarContent.tsx +++ b/src/components/AppbarV3/AppbarContent.tsx @@ -17,6 +17,7 @@ type Props = Pick< | 'subtitle' | 'subtitleProps' | 'title' + | 'titleActionProps' | 'titleImage' | 'titleProps' > & { @@ -54,6 +55,7 @@ const AppbarContent = ({ testID, theme, title, + titleActionProps, titleImage, titleProps, variant, @@ -80,7 +82,7 @@ const AppbarContent = ({ theme={theme} variant={titleVariant} numberOfLines={variant === 'small' ? 1 : 2} - role={onTitlePress ? 'none' : 'heading'} + role="heading" accessible maxFontSizeMultiplier={titleProps?.maxFontSizeMultiplier} testID={`${testID}-title-text`} @@ -126,11 +128,27 @@ const AppbarContent = ({ }; if (onTitlePress) { + const { + 'aria-label': ariaLabel, + accessibilityLabel, + disabled, + ...restTitleActionProps + } = titleActionProps ?? {}; + return ( {content} diff --git a/src/components/AppbarV3/index.ts b/src/components/AppbarV3/index.ts index 06fb7c8533..ec24e51cb1 100644 --- a/src/components/AppbarV3/index.ts +++ b/src/components/AppbarV3/index.ts @@ -8,6 +8,7 @@ export type { AppbarSearchbarProps, AppbarStandardAction, AppbarTextProps, + AppbarTitleActionProps, AppbarTitleAlignment, AppbarTitleTextProps, AppbarVariant, diff --git a/src/components/AppbarV3/types.ts b/src/components/AppbarV3/types.ts index 6f945f8156..e1356c45ef 100644 --- a/src/components/AppbarV3/types.ts +++ b/src/components/AppbarV3/types.ts @@ -38,12 +38,33 @@ export type AppbarTitleTextProps = AppbarTextProps & { ref?: React.RefObject; }; +export type AppbarTitleActionProps = Pick< + ViewProps, + | 'accessibilityActions' + | 'accessibilityHint' + | 'accessibilityLabel' + | 'accessibilityLabelledBy' + | 'accessibilityLanguage' + | 'accessibilityState' + | 'accessibilityValue' + | 'aria-busy' + | 'aria-disabled' + | 'aria-expanded' + | 'aria-label' + | 'aria-labelledby' + | 'aria-selected' + | 'onAccessibilityAction' +> & { + /** Whether the title action is disabled. */ + disabled?: boolean; +}; + type AppbarActionBase = Omit< IconButtonProps, 'icon' | 'iconColor' | 'mode' | 'selected' | 'size' | 'theme' | 'aria-label' > & { /** Stable key used when rendering an action from the actions array. */ - key?: React.Key; + key: React.Key; /** Icon displayed by the action. */ icon: IconSource; /** Accessible label announced for the icon button. */ @@ -71,17 +92,19 @@ export type AppbarActions = | readonly AppbarStandardAction[] | readonly [AppbarFilledAction]; -type AppbarLeadingIconAction = AppbarStandardAction & { +type AppbarLeadingIconAction = Omit & { + key?: never; type?: 'icon'; }; type AppbarBackAction = Omit< AppbarStandardAction, - 'aria-label' | 'icon' | 'type' + 'aria-label' | 'icon' | 'key' | 'type' > & { /** Uses the platform-aware Paper back icon. */ type: 'back'; icon?: never; + key?: never; 'aria-label'?: string; }; @@ -122,7 +145,16 @@ type AppbarFlexibleImageTitle = AppbarWrittenTitle & variant: Exclude; }; -type AppbarBaseProps = Omit & { +type AppbarBaseProps = Omit< + ViewProps, + | 'accessibilityLabel' + | 'accessibilityRole' + | 'accessible' + | 'aria-label' + | 'children' + | 'role' + | 'style' +> & { /** Optional leading navigation action. */ leadingAction?: AppbarLeadingAction; /** Uses the on-scroll container color when true. */ @@ -145,12 +177,21 @@ type AppbarTitleProps = { titleAlignment?: AppbarTitleAlignment; /** Trailing icon actions. */ actions?: AppbarActions; - /** Called when the title area is pressed. */ - onTitlePress?: (event: GestureResponderEvent) => void; /** Style applied to the title area. */ contentStyle?: StyleProp; searchBar?: never; -}; +} & ( + | { + /** Called when the title area is pressed. */ + onTitlePress: (event: GestureResponderEvent) => void; + /** Accessibility props applied to the interactive title area. */ + titleActionProps?: AppbarTitleActionProps; + } + | { + onTitlePress?: never; + titleActionProps?: never; + } +); export type AppbarSearchbarProps = Omit< SearchbarProps, @@ -173,6 +214,7 @@ type AppbarSearchProps = { titleProps?: never; subtitleProps?: never; onTitlePress?: never; + titleActionProps?: never; contentStyle?: never; }; diff --git a/src/index.tsx b/src/index.tsx index 1726a497ec..0f90db1c07 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -70,6 +70,7 @@ export type { AppbarSearchbarProps as AppbarV3SearchbarProps, AppbarStandardAction as AppbarV3StandardAction, AppbarTextProps as AppbarV3TextProps, + AppbarTitleActionProps as AppbarV3TitleActionProps, AppbarTitleAlignment as AppbarV3TitleAlignment, AppbarTitleTextProps as AppbarV3TitleTextProps, AppbarVariant as AppbarV3Variant, From 40d3947486d38e020d993b64906891f61c19b482 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Tue, 25 Aug 2026 09:53:14 +0200 Subject: [PATCH 16/20] test(appbar): accessibility related tests --- .../__tests__/AppbarV3/AppbarV3.test.tsx | 259 ++++++++++++++++++ 1 file changed, 259 insertions(+) create mode 100644 src/components/__tests__/AppbarV3/AppbarV3.test.tsx diff --git a/src/components/__tests__/AppbarV3/AppbarV3.test.tsx b/src/components/__tests__/AppbarV3/AppbarV3.test.tsx new file mode 100644 index 0000000000..287d449ed7 --- /dev/null +++ b/src/components/__tests__/AppbarV3/AppbarV3.test.tsx @@ -0,0 +1,259 @@ +import { Text, View } from 'react-native'; + +import { describe, expect, it, jest } from '@jest/globals'; + +import { render, screen } from '../../../test-utils'; +import AppbarV3 from '../../AppbarV3'; +import type { AppbarVariant } from '../../AppbarV3'; + +const writtenTitleVariants: Exclude[] = [ + 'small', + 'medium-flexible', + 'large-flexible', +]; + +const decorativeTitleImage = ( + + + + Brand words + + +); + +describe('AppbarV3 accessibility', () => { + it.each(writtenTitleVariants)( + 'exposes a written %s title as a heading', + async (variant) => { + await render(); + + expect(screen.getByRole('heading', { name: 'Inbox' })).toBeOnTheScreen(); + } + ); + + it('hides a small title image behind one named heading', async () => { + await render( + + ); + + expect(screen.getAllByRole('heading')).toHaveLength(1); + expect(screen.getByRole('heading', { name: 'Inbox' })).toBeOnTheScreen(); + expect(screen.queryByRole('img')).not.toBeOnTheScreen(); + expect(screen.queryByText('Brand words')).not.toBeOnTheScreen(); + }); + + it.each(['medium-flexible', 'large-flexible'] as const)( + 'does not expose duplicate content for a %s title image', + async (variant) => { + await render( + + ); + + expect(screen.getAllByRole('heading', { name: 'Inbox' })).toHaveLength(1); + expect(screen.queryByRole('img')).not.toBeOnTheScreen(); + expect(screen.queryByLabelText('Brand artwork')).not.toBeOnTheScreen(); + } + ); + + it('exposes a pressable written title as a named button and heading', async () => { + const onTitlePress = jest.fn(); + await render( + + ); + + expect(screen.getByRole('button', { name: 'Inbox' })).toBeOnTheScreen(); + expect(screen.getByRole('heading', { name: 'Inbox' })).toBeOnTheScreen(); + }); + + it('forwards custom title button accessibility props', async () => { + const onAccessibilityAction = jest.fn(); + await render( + {}} + titleActionProps={{ + accessibilityActions: [{ name: 'activate', label: 'Open inbox' }], + accessibilityHint: 'Opens the inbox menu', + accessibilityLabel: 'Inbox options', + accessibilityState: { busy: true, expanded: true }, + accessibilityValue: { text: 'Unread messages available' }, + onAccessibilityAction, + }} + /> + ); + + const titleButton = screen.getByRole('button', { + name: 'Inbox options', + busy: true, + expanded: true, + }); + + expect(titleButton).toHaveProp( + 'accessibilityActions', + expect.arrayContaining([ + expect.objectContaining({ name: 'activate', label: 'Open inbox' }), + ]) + ); + expect(titleButton).toHaveProp('accessibilityHint', 'Opens the inbox menu'); + expect(titleButton).toHaveAccessibilityValue({ + text: 'Unread messages available', + }); + expect(titleButton).toHaveProp( + 'onAccessibilityAction', + onAccessibilityAction + ); + }); + + it('uses default and custom labels for back actions', async () => { + await render( + + + + + ); + + expect(screen.getByRole('button', { name: 'Back' })).toBeOnTheScreen(); + expect( + screen.getByRole('button', { name: 'Return to inbox' }) + ).toBeOnTheScreen(); + }); + + it('preserves icon action labels, hints, disabled state, and busy state', async () => { + await render( + + ); + + const action = screen.getByRole('button', { + name: 'Save message', + busy: true, + disabled: true, + }); + + expect(action).toHaveProp('accessibilityHint', 'Saves the current draft'); + expect(action).toBeDisabled(); + expect(action).toBeBusy(); + }); + + it.each(['small', 'medium-flexible'] as const)( + 'hides decorative descendants of a %s title image', + async (variant) => { + await render( + variant === 'small' ? ( + + ) : ( + + ) + ); + + const imageContainer = screen.getByTestId('appbar-content-title-image', { + includeHiddenElements: true, + }); + + expect(imageContainer).toHaveProp('aria-hidden', true); + expect(imageContainer).toHaveProp( + 'importantForAccessibility', + 'no-hide-descendants' + ); + expect( + screen.queryByRole('heading', { name: 'Brand words' }) + ).not.toBeOnTheScreen(); + } + ); + + it('exposes leading, title, and trailing elements in source order', async () => { + await render( + + ); + + expect(screen.getAllByRole(/button|heading/)).toEqual([ + screen.getByRole('button', { name: 'Navigate back' }), + screen.getByRole('heading', { name: 'Inbox' }), + screen.getByRole('button', { name: 'Search inbox' }), + screen.getByRole('button', { name: 'More options' }), + ]); + }); + + it('does not remount a surviving action when its configuration changes', async () => { + const { rerender } = await render( + + ); + const survivingAction = screen.getByRole('button', { + name: 'Keep action', + }); + + await rerender( + + ); + + expect(screen.getByRole('button', { name: 'Keep action' })).toBe( + survivingAction + ); + }); +}); From 1b77102da6f7d91df69f802a4630cdf9ae2a87ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Tue, 25 Aug 2026 10:24:06 +0200 Subject: [PATCH 17/20] refactor(appbar): rename props to match M3 conventions --- example/src/Examples/AppbarV3Example.tsx | 158 +++++++++--------- src/components/AppbarV3/Appbar.tsx | 110 ++++++------ .../{AppbarAction.tsx => AppbarButton.tsx} | 25 ++- src/components/AppbarV3/AppbarContent.tsx | 90 +++++----- src/components/AppbarV3/index.ts | 16 +- src/components/AppbarV3/types.ts | 130 +++++++------- src/components/AppbarV3/utils.ts | 16 +- .../__tests__/AppbarV3/AppbarV3.test.tsx | 106 ++++++------ src/index.tsx | 16 +- 9 files changed, 347 insertions(+), 320 deletions(-) rename src/components/AppbarV3/{AppbarAction.tsx => AppbarButton.tsx} (67%) diff --git a/example/src/Examples/AppbarV3Example.tsx b/example/src/Examples/AppbarV3Example.tsx index c3734b6712..e737fcae64 100644 --- a/example/src/Examples/AppbarV3Example.tsx +++ b/example/src/Examples/AppbarV3Example.tsx @@ -19,33 +19,35 @@ import { Text, } from 'react-native-paper'; import type { - AppbarV3Actions, - AppbarV3FilledAction, - AppbarV3LeadingAction, - AppbarV3StandardAction, - AppbarV3TitleAlignment, + AppbarV3FilledTrailingAction, + AppbarV3HeadlineAlignment, + AppbarV3LeadingButton, + AppbarV3StandardTrailingAction, + AppbarV3TrailingActions, AppbarV3Variant, } from 'react-native-paper'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import ScreenWrapper from '../ScreenWrapper'; -type FilledActionVariant = AppbarV3FilledAction['variant']; -type FilledActionWidth = NonNullable; +type FilledTrailingActionVariant = AppbarV3FilledTrailingAction['variant']; +type FilledTrailingActionWidth = NonNullable< + AppbarV3FilledTrailingAction['width'] +>; const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical'; type SearchAppbarHeaderProps = { - actions: AppbarV3StandardAction[]; + trailingActions: AppbarV3StandardTrailingAction[]; isScrolled: boolean; - leadingAction?: AppbarV3LeadingAction; + leadingButton?: AppbarV3LeadingButton; showCustomColor: boolean; }; const SearchAppbarHeader = ({ - actions, + trailingActions, isScrolled, - leadingAction, + leadingButton, showCustomColor, }: SearchAppbarHeaderProps) => { const [searchQuery, setSearchQuery] = React.useState(''); @@ -53,10 +55,10 @@ const SearchAppbarHeader = ({ return ( { const navigation = useNavigation('AppbarV3'); - const [showLeftIcon, setShowLeftIcon] = React.useState(true); + const [showLeadingButton, setShowLeadingButton] = React.useState(true); const [showSubtitle, setShowSubtitle] = React.useState(true); - const [showTitleImage, setShowTitleImage] = React.useState(false); + const [showHeadlineImage, setShowHeadlineImage] = React.useState(false); const [showSearchIcon, setShowSearchIcon] = React.useState(true); const [showMoreIcon, setShowMoreIcon] = React.useState(true); const [showCustomColor, setShowCustomColor] = React.useState(false); const [appbarConfiguration, setAppbarConfiguration] = React.useState('small'); - const [isTitleCentered, setIsTitleCentered] = React.useState(false); + const [isHeadlineCentered, setIsHeadlineCentered] = React.useState(false); const [showCalendarIcon, setShowCalendarIcon] = React.useState(false); - const [showFilledAction, setShowFilledAction] = React.useState(false); - const [filledActionVariant, setFilledActionVariant] = - React.useState('filled'); - const [filledActionWidth, setFilledActionWidth] = - React.useState('default'); + const [showFilledTrailingAction, setShowFilledTrailingAction] = + React.useState(false); + const [filledTrailingActionVariant, setFilledTrailingActionVariant] = + React.useState('filled'); + const [filledTrailingActionWidth, setFilledTrailingActionWidth] = + React.useState('default'); const [isScrolled, setIsScrolled] = React.useState(false); const [showSnackbar, setShowSnackbar] = React.useState(false); const { bottom } = useSafeAreaInsets(); const { height: windowHeight } = useWindowDimensions(); - const titleAlignment: AppbarV3TitleAlignment = isTitleCentered + const headlineAlignment: AppbarV3HeadlineAlignment = isHeadlineCentered ? 'center' : 'leading'; React.useLayoutEffect(() => { - const standardActions: AppbarV3StandardAction[] = []; + const standardTrailingActions: AppbarV3StandardTrailingAction[] = []; if (showCalendarIcon) { - standardActions.push({ + standardTrailingActions.push({ key: 'calendar', icon: 'calendar', 'aria-label': 'Calendar', @@ -107,7 +110,7 @@ const AppbarV3Example = () => { } if (showSearchIcon && appbarConfiguration !== 'search') { - standardActions.push({ + standardTrailingActions.push({ key: 'search', icon: 'magnify', 'aria-label': 'Search', @@ -116,7 +119,7 @@ const AppbarV3Example = () => { } if (showMoreIcon) { - standardActions.push({ + standardTrailingActions.push({ key: 'more', icon: MORE_ICON, 'aria-label': 'More options', @@ -124,40 +127,40 @@ const AppbarV3Example = () => { }); } - const actions: AppbarV3Actions = showFilledAction + const trailingActions: AppbarV3TrailingActions = showFilledTrailingAction ? [ { key: 'share', icon: 'share-variant', 'aria-label': 'Share', - variant: filledActionVariant, - width: filledActionWidth, + variant: filledTrailingActionVariant, + width: filledTrailingActionWidth, onPress: () => {}, }, ] - : standardActions; + : standardTrailingActions; - const leadingAction = showLeftIcon + const leadingButton = showLeadingButton ? { type: 'back' as const, onPress: () => navigation.goBack(), } : undefined; - const titleImage = ( + const headlineImage = ( ); const commonProps = { - actions, + headlineAlignment, isScrolled, - leadingAction, - onTitlePress: () => setShowSnackbar(true), + leadingButton, + onHeadlinePress: () => setShowSnackbar(true), style: showCustomColor ? styles.customColor : null, - titleAlignment, + trailingActions, }; navigation.setOptions({ @@ -165,27 +168,27 @@ const AppbarV3Example = () => { if (appbarConfiguration === 'search') { return ( ); } if (appbarConfiguration === 'small') { - return showTitleImage ? ( + return showHeadlineImage ? ( ) : ( { ); } - return showTitleImage ? ( + return showHeadlineImage ? ( { { }); }, [ appbarConfiguration, - filledActionVariant, - filledActionWidth, + filledTrailingActionVariant, + filledTrailingActionWidth, navigation, showCalendarIcon, showCustomColor, - showFilledAction, - showLeftIcon, + showFilledTrailingAction, + showLeadingButton, showMoreIcon, isScrolled, showSearchIcon, showSubtitle, - showTitleImage, - titleAlignment, + showHeadlineImage, + headlineAlignment, ]); const handleScroll = React.useCallback( @@ -248,8 +251,11 @@ const AppbarV3Example = () => { const renderDefaultOptions = () => ( <> - Left icon - + Leading button + Subtitle @@ -257,40 +263,42 @@ const AppbarV3Example = () => { value={showSubtitle} disabled={ appbarConfiguration === 'search' || - (showTitleImage && appbarConfiguration === 'small') + (showHeadlineImage && appbarConfiguration === 'small') } onValueChange={setShowSubtitle} /> - Title image + Headline image - Center title and subtitle + Center headline and subtitle Filled trailing action Search icon @@ -298,7 +306,7 @@ const AppbarV3Example = () => { More icon @@ -306,7 +314,7 @@ const AppbarV3Example = () => { Calendar icon @@ -339,14 +347,14 @@ const AppbarV3Example = () => { {renderDefaultOptions()} - {showFilledAction ? ( - + {showFilledTrailingAction ? ( + Style { if (value === 'filled' || value === 'tonal') { - setFilledActionVariant(value); + setFilledTrailingActionVariant(value); } }} > @@ -361,10 +369,10 @@ const AppbarV3Example = () => { Width { if (value === 'default' || value === 'wide') { - setFilledActionWidth(value); + setFilledTrailingActionWidth(value); } }} > @@ -417,7 +425,7 @@ const AppbarV3Example = () => { onDismiss={() => setShowSnackbar(false)} duration={Snackbar.DURATION_SHORT} > - Heading pressed + Headline pressed ); @@ -441,7 +449,7 @@ const styles = StyleSheet.create({ customColor: { backgroundColor: Palette.secondary80, }, - titleImage: { + headlineImage: { width: 32, height: 32, }, diff --git a/src/components/AppbarV3/Appbar.tsx b/src/components/AppbarV3/Appbar.tsx index 69a208ee30..b663f852b7 100644 --- a/src/components/AppbarV3/Appbar.tsx +++ b/src/components/AppbarV3/Appbar.tsx @@ -4,15 +4,15 @@ import type { ColorValue, LayoutChangeEvent, ViewProps } from 'react-native'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; -import AppbarAction from './AppbarAction'; +import AppbarButton from './AppbarButton'; import AppbarContent from './AppbarContent'; import type { Props } from './types'; import { - APPBAR_ACTION_SIZE, - APPBAR_TITLE_IMAGE_HEIGHT, - getActionsWidth, + APPBAR_HEADLINE_IMAGE_HEIGHT, + APPBAR_ICON_BUTTON_SIZE, getAppbarHeight, getAppbarSearchWidth, + getTrailingActionsWidth, } from './utils'; import { useInternalTheme } from '../../core/theming'; import { getAppbarBorders } from '../Appbar/utils'; @@ -20,11 +20,15 @@ import Searchbar from '../Searchbar'; import Surface from '../Surface'; const Appbar = ({ - actions = [], contentStyle, + headline, + headlineAlignment = 'leading', + headlineImage, + headlinePressableProps, + headlineProps, isScrolled = false, - leadingAction, - onTitlePress, + leadingButton, + onHeadlinePress, safeAreaInsets, searchBar, statusBarHeight, @@ -33,11 +37,7 @@ const Appbar = ({ subtitleProps, testID = 'appbar', theme: themeOverrides, - title, - titleActionProps, - titleAlignment = 'leading', - titleImage, - titleProps, + trailingActions = [], variant, ref, ...rest @@ -64,7 +64,7 @@ const Appbar = ({ const rightInset = safeAreaInsets?.right ?? detectedInsets.right; const horizontalInset = Math.max(leftInset, rightInset); const borderRadius = getAppbarBorders(restStyle); - const centered = titleAlignment === 'center'; + const centered = headlineAlignment === 'center'; const { accessibilityLabel: _accessibilityLabel, accessibilityRole: _accessibilityRole, @@ -85,14 +85,14 @@ const Appbar = ({ [] ); - const renderLeadingAction = () => - leadingAction ? ( - + const renderLeadingButton = () => + leadingButton ? ( + ) : null; - const renderActions = () => - actions.map((action) => ( - + const renderTrailingActions = () => + trailingActions.map((action) => ( + )); const renderSearchAppbar = () => { @@ -115,7 +115,7 @@ const Appbar = ({ return ( - {renderLeadingAction()} + {renderLeadingButton()} - {renderActions()} + {renderTrailingActions()} ); }; @@ -152,30 +152,30 @@ const Appbar = ({ const contentProps = variant !== 'search' ? { - alignment: titleAlignment, + alignment: headlineAlignment, contentStyle, - onTitlePress, + headline, + headlineImage, + headlinePressableProps, + headlineProps, + onHeadlinePress, subtitle, subtitleProps, testID: `${testID}-content`, theme, - title, - titleActionProps, - titleImage, - titleProps, variant, } : null; - const renderFlexibleTitleImage = () => - titleImage ? ( + const renderFlexibleHeadlineImage = () => + headlineImage ? ( - {titleImage} + {headlineImage} ) : null; @@ -184,22 +184,22 @@ const Appbar = ({ return null; } - if (centered || titleImage) { + if (centered || headlineImage) { const sideWidth = Math.max( - leadingAction ? APPBAR_ACTION_SIZE : 0, - getActionsWidth(actions) + leadingButton ? APPBAR_ICON_BUTTON_SIZE : 0, + getTrailingActionsWidth(trailingActions) ); return ( - {renderLeadingAction()} + {renderLeadingButton()} - {renderActions()} + {renderTrailingActions()} ); @@ -207,12 +207,14 @@ const Appbar = ({ return ( - {renderLeadingAction()} + {renderLeadingButton()} - {renderActions()} + {renderTrailingActions()} ); }; @@ -223,18 +225,18 @@ const Appbar = ({ } const sideWidth = Math.max( - leadingAction ? APPBAR_ACTION_SIZE : 0, - getActionsWidth(actions) + leadingButton ? APPBAR_ICON_BUTTON_SIZE : 0, + getTrailingActionsWidth(trailingActions) ); return ( - {titleImage ? ( + {headlineImage ? ( - {renderLeadingAction()} + {renderLeadingButton()} - {renderFlexibleTitleImage()} + {renderFlexibleHeadlineImage()} - {renderActions()} + {renderTrailingActions()} ) : ( - {renderLeadingAction()} - {renderActions()} + {renderLeadingButton()} + + {renderTrailingActions()} + )} - + ); }; @@ -328,15 +332,15 @@ const styles = StyleSheet.create({ side: { flexDirection: 'row', }, - titleLeading: { + headlineLeading: { marginStart: 12, }, - titleWithLeading: { + headlineWithLeading: { marginStart: 4, }, - flexibleTitleImage: { + flexibleHeadlineImage: { flex: 1, - height: APPBAR_TITLE_IMAGE_HEIGHT, + height: APPBAR_HEADLINE_IMAGE_HEIGHT, maxWidth: '100%', marginTop: 12, alignItems: 'center', diff --git a/src/components/AppbarV3/AppbarAction.tsx b/src/components/AppbarV3/AppbarButton.tsx similarity index 67% rename from src/components/AppbarV3/AppbarAction.tsx rename to src/components/AppbarV3/AppbarButton.tsx index 6889d45948..251190aa91 100644 --- a/src/components/AppbarV3/AppbarAction.tsx +++ b/src/components/AppbarV3/AppbarButton.tsx @@ -1,20 +1,17 @@ import { StyleSheet } from 'react-native'; -import type { - AppbarAction as AppbarActionConfig, - AppbarLeadingAction, -} from './types'; +import type { AppbarLeadingButton, AppbarTrailingAction } from './types'; import type { Theme } from '../../types'; import AppbarBackIcon from '../Appbar/AppbarBackIcon'; import IconButton from '../IconButton/IconButton'; type Props = { - action: AppbarActionConfig | AppbarLeadingAction; + button: AppbarTrailingAction | AppbarLeadingButton; leading?: boolean; theme: Theme; }; -const AppbarAction = ({ action, leading = false, theme }: Props) => { +const AppbarButton = ({ button, leading = false, theme }: Props) => { const { color, key: _key, @@ -22,11 +19,11 @@ const AppbarAction = ({ action, leading = false, theme }: Props) => { variant = 'standard', width, ...rest - } = action; + } = button; const { type: _type, ...buttonProps } = rest as typeof rest & { type?: 'back' | 'icon'; }; - const isBackAction = 'type' in action && action.type === 'back'; + const isBackButton = 'type' in button && button.type === 'back'; const mode = variant === 'filled' ? 'contained' @@ -44,28 +41,28 @@ const AppbarAction = ({ action, leading = false, theme }: Props) => { return ( ); }; const styles = StyleSheet.create({ - action: { + button: { margin: 4, }, - wideAction: { + wideButton: { width: 56, }, }); -export default AppbarAction; +export default AppbarButton; diff --git a/src/components/AppbarV3/AppbarContent.tsx b/src/components/AppbarV3/AppbarContent.tsx index a1118a63c4..bba1db657e 100644 --- a/src/components/AppbarV3/AppbarContent.tsx +++ b/src/components/AppbarV3/AppbarContent.tsx @@ -2,98 +2,98 @@ import { Pressable, StyleSheet, View } from 'react-native'; import type { StyleProp, ViewStyle } from 'react-native'; import type { - AppbarTitleAlignment, - AppbarTitleVariant, + AppbarHeadlineAlignment, + AppbarHeadlineVariant, Props as AppbarProps, } from './types'; -import { APPBAR_TITLE_IMAGE_HEIGHT } from './utils'; +import { APPBAR_HEADLINE_IMAGE_HEIGHT } from './utils'; import type { Theme, TypescaleKey } from '../../types'; import Text from '../Typography/Text'; type Props = Pick< AppbarProps, | 'contentStyle' - | 'onTitlePress' + | 'headline' + | 'headlineImage' + | 'headlinePressableProps' + | 'headlineProps' + | 'onHeadlinePress' | 'subtitle' | 'subtitleProps' - | 'title' - | 'titleActionProps' - | 'titleImage' - | 'titleProps' > & { - alignment: AppbarTitleAlignment; + alignment: AppbarHeadlineAlignment; theme: Theme; - variant: AppbarTitleVariant; + variant: AppbarHeadlineVariant; style?: StyleProp; testID: string; }; -const titleVariants = { +const headlineVariants = { small: 'titleLarge', 'medium-flexible': 'headlineMedium', 'large-flexible': 'displaySmall', -} as const satisfies Record; +} as const satisfies Record; const subtitleVariants = { small: 'labelMedium', 'medium-flexible': 'labelLarge', 'large-flexible': 'titleMedium', -} as const satisfies Record; +} as const satisfies Record; const subtitleSpacing = { small: 0, 'medium-flexible': 4, 'large-flexible': 8, -} as const satisfies Record; +} as const satisfies Record; const AppbarContent = ({ alignment, contentStyle, - onTitlePress, + headline, + headlineImage, + headlinePressableProps, + headlineProps, + onHeadlinePress, subtitle, subtitleProps, testID, theme, - title, - titleActionProps, - titleImage, - titleProps, variant, style, }: Props) => { - const titleVariant = titleVariants[variant]; + const headlineVariant = headlineVariants[variant]; const subtitleVariant = subtitleVariants[variant]; const centered = alignment === 'center'; - const hasTitleImage = variant === 'small' && Boolean(titleImage); + const hasHeadlineImage = variant === 'small' && Boolean(headlineImage); - const content = hasTitleImage ? ( + const content = hasHeadlineImage ? ( - {titleImage} + {headlineImage} ) : ( <> - {title} + {headline} {subtitle ? ( {content} @@ -159,9 +161,9 @@ const AppbarContent = ({ return ( {content} @@ -189,8 +191,8 @@ const styles = StyleSheet.create({ centeredText: { textAlign: 'center', }, - titleImage: { - height: APPBAR_TITLE_IMAGE_HEIGHT, + headlineImage: { + height: APPBAR_HEADLINE_IMAGE_HEIGHT, maxWidth: '100%', alignItems: 'center', justifyContent: 'center', diff --git a/src/components/AppbarV3/index.ts b/src/components/AppbarV3/index.ts index ec24e51cb1..d8ba839263 100644 --- a/src/components/AppbarV3/index.ts +++ b/src/components/AppbarV3/index.ts @@ -1,16 +1,16 @@ export { default } from './Appbar'; export { Appbar } from './Appbar'; export type { - AppbarAction, - AppbarActions, - AppbarFilledAction, - AppbarLeadingAction, + AppbarFilledTrailingAction, + AppbarHeadlineAlignment, + AppbarHeadlinePressableProps, + AppbarHeadlineTextProps, + AppbarLeadingButton, AppbarSearchbarProps, - AppbarStandardAction, + AppbarStandardTrailingAction, AppbarTextProps, - AppbarTitleActionProps, - AppbarTitleAlignment, - AppbarTitleTextProps, + AppbarTrailingAction, + AppbarTrailingActions, AppbarVariant, Props, } from './types'; diff --git a/src/components/AppbarV3/types.ts b/src/components/AppbarV3/types.ts index e1356c45ef..4696a7bb27 100644 --- a/src/components/AppbarV3/types.ts +++ b/src/components/AppbarV3/types.ts @@ -22,9 +22,9 @@ export type AppbarVariant = | 'medium-flexible' | 'large-flexible'; -export type AppbarTitleVariant = Exclude; +export type AppbarHeadlineVariant = Exclude; -export type AppbarTitleAlignment = 'leading' | 'center'; +export type AppbarHeadlineAlignment = 'leading' | 'center'; export type AppbarTextProps = { /** Style applied to the text. */ @@ -33,12 +33,12 @@ export type AppbarTextProps = { maxFontSizeMultiplier?: number; }; -export type AppbarTitleTextProps = AppbarTextProps & { - /** Reference for the title heading. */ +export type AppbarHeadlineTextProps = AppbarTextProps & { + /** Reference for the headline heading. */ ref?: React.RefObject; }; -export type AppbarTitleActionProps = Pick< +export type AppbarHeadlinePressableProps = Pick< ViewProps, | 'accessibilityActions' | 'accessibilityHint' @@ -55,50 +55,52 @@ export type AppbarTitleActionProps = Pick< | 'aria-selected' | 'onAccessibilityAction' > & { - /** Whether the title action is disabled. */ + /** Whether the headline interaction is disabled. */ disabled?: boolean; }; -type AppbarActionBase = Omit< +type AppbarTrailingActionBase = Omit< IconButtonProps, 'icon' | 'iconColor' | 'mode' | 'selected' | 'size' | 'theme' | 'aria-label' > & { - /** Stable key used when rendering an action from the actions array. */ + /** Stable key used when rendering an action from the trailing actions array. */ key: React.Key; - /** Icon displayed by the action. */ + /** Icon displayed by the trailing action. */ icon: IconSource; /** Accessible label announced for the icon button. */ 'aria-label': string; - /** Custom action icon color. */ + /** Custom trailing action icon color. */ color?: ColorValue; }; -export type AppbarStandardAction = AppbarActionBase & { +export type AppbarStandardTrailingAction = AppbarTrailingActionBase & { variant?: 'standard'; width?: never; }; -export type AppbarFilledAction = AppbarActionBase & { - /** Filled primary and tonal actions use the corresponding IconButton colors. */ +export type AppbarFilledTrailingAction = AppbarTrailingActionBase & { + /** Filled primary and tonal icons use the corresponding IconButton colors. */ variant: 'filled' | 'tonal'; - /** Expressive filled actions can use the default or wide container. */ + /** Expressive filled icons can use the default or wide container. */ width?: 'default' | 'wide'; }; -export type AppbarAction = AppbarStandardAction | AppbarFilledAction; +export type AppbarTrailingAction = + | AppbarStandardTrailingAction + | AppbarFilledTrailingAction; -/** A filled action replaces the standard action group and is valid on its own. */ -export type AppbarActions = - | readonly AppbarStandardAction[] - | readonly [AppbarFilledAction]; +/** A filled trailing action replaces the standard action group and is valid on its own. */ +export type AppbarTrailingActions = + | readonly AppbarStandardTrailingAction[] + | readonly [AppbarFilledTrailingAction]; -type AppbarLeadingIconAction = Omit & { +type AppbarLeadingIconButton = Omit & { key?: never; type?: 'icon'; }; -type AppbarBackAction = Omit< - AppbarStandardAction, +type AppbarBackButton = Omit< + AppbarStandardTrailingAction, 'aria-label' | 'icon' | 'key' | 'type' > & { /** Uses the platform-aware Paper back icon. */ @@ -108,41 +110,41 @@ type AppbarBackAction = Omit< 'aria-label'?: string; }; -export type AppbarLeadingAction = AppbarLeadingIconAction | AppbarBackAction; +export type AppbarLeadingButton = AppbarLeadingIconButton | AppbarBackButton; -type AppbarWrittenTitle = { +type AppbarWrittenHeadline = { /** Written headline displayed by the app bar. */ - title: string; + headline: string; /** Optional supporting text displayed below the headline. */ subtitle?: string; - /** Props applied to the title heading. */ - titleProps?: AppbarTitleTextProps; + /** Props applied to the headline heading. */ + headlineProps?: AppbarHeadlineTextProps; /** Props applied to the subtitle text. */ subtitleProps?: AppbarTextProps; }; -type AppbarTitleImage = { +type AppbarHeadlineImage = { /** Image or logo displayed in the app bar. It should fit within 32dp height. */ - titleImage: React.ReactElement; + headlineImage: React.ReactElement; }; -type AppbarTextTitle = AppbarWrittenTitle & { - variant: AppbarTitleVariant; - titleImage?: never; +type AppbarTextHeadline = AppbarWrittenHeadline & { + variant: AppbarHeadlineVariant; + headlineImage?: never; }; -type AppbarSmallImageTitle = AppbarTitleImage & { +type AppbarSmallImageHeadline = AppbarHeadlineImage & { variant: 'small'; - /** Accessible page title. The image replaces this text visually. */ - title: string; + /** Accessible page headline. The image replaces this text visually. */ + headline: string; subtitle?: never; - titleProps?: never; + headlineProps?: never; subtitleProps?: never; }; -type AppbarFlexibleImageTitle = AppbarWrittenTitle & - AppbarTitleImage & { - variant: Exclude; +type AppbarFlexibleImageHeadline = AppbarWrittenHeadline & + AppbarHeadlineImage & { + variant: Exclude; }; type AppbarBaseProps = Omit< @@ -155,8 +157,8 @@ type AppbarBaseProps = Omit< | 'role' | 'style' > & { - /** Optional leading navigation action. */ - leadingAction?: AppbarLeadingAction; + /** Optional leading button. */ + leadingButton?: AppbarLeadingButton; /** Uses the on-scroll container color when true. */ isScrolled?: boolean; /** Override for the automatic top safe-area inset. */ @@ -172,24 +174,24 @@ type AppbarBaseProps = Omit< theme?: ThemeProp; }; -type AppbarTitleProps = { +type AppbarHeadlineProps = { /** Headline and subtitle alignment. */ - titleAlignment?: AppbarTitleAlignment; - /** Trailing icon actions. */ - actions?: AppbarActions; - /** Style applied to the title area. */ + headlineAlignment?: AppbarHeadlineAlignment; + /** Trailing actions. */ + trailingActions?: AppbarTrailingActions; + /** Style applied to the headline and subtitle area. */ contentStyle?: StyleProp; searchBar?: never; } & ( | { - /** Called when the title area is pressed. */ - onTitlePress: (event: GestureResponderEvent) => void; - /** Accessibility props applied to the interactive title area. */ - titleActionProps?: AppbarTitleActionProps; + /** Called when the headline area is pressed. */ + onHeadlinePress: (event: GestureResponderEvent) => void; + /** Props applied to the interactive headline area. */ + headlinePressableProps?: AppbarHeadlinePressableProps; } | { - onTitlePress?: never; - titleActionProps?: never; + onHeadlinePress?: never; + headlinePressableProps?: never; } ); @@ -205,22 +207,26 @@ type AppbarSearchProps = { variant: 'search'; /** Props forwarded to the existing Paper Searchbar. */ searchBar: AppbarSearchbarProps; - /** Exterior trailing icon actions. */ - actions?: readonly AppbarStandardAction[]; - title?: never; + /** Exterior trailing actions. */ + trailingActions?: readonly AppbarStandardTrailingAction[]; + headline?: never; subtitle?: never; - titleImage?: never; - titleAlignment?: never; - titleProps?: never; + headlineImage?: never; + headlineAlignment?: never; + headlineProps?: never; subtitleProps?: never; - onTitlePress?: never; - titleActionProps?: never; + onHeadlinePress?: never; + headlinePressableProps?: never; contentStyle?: never; }; export type Props = AppbarBaseProps & ( - | (AppbarTitleProps & - (AppbarTextTitle | AppbarSmallImageTitle | AppbarFlexibleImageTitle)) + | (AppbarHeadlineProps & + ( + | AppbarTextHeadline + | AppbarSmallImageHeadline + | AppbarFlexibleImageHeadline + )) | AppbarSearchProps ); diff --git a/src/components/AppbarV3/utils.ts b/src/components/AppbarV3/utils.ts index 219f0d6cca..6ab0c7b02f 100644 --- a/src/components/AppbarV3/utils.ts +++ b/src/components/AppbarV3/utils.ts @@ -1,8 +1,8 @@ -import type { AppbarAction, AppbarVariant } from './types'; +import type { AppbarTrailingAction, AppbarVariant } from './types'; -export const APPBAR_ACTION_SIZE = 48; -export const APPBAR_WIDE_ACTION_SIZE = 64; -export const APPBAR_TITLE_IMAGE_HEIGHT = 32; +export const APPBAR_ICON_BUTTON_SIZE = 48; +export const APPBAR_WIDE_ICON_BUTTON_SIZE = 64; +export const APPBAR_HEADLINE_IMAGE_HEIGHT = 32; export const APPBAR_SEARCH_MIN_WIDTH = 360; export const APPBAR_SEARCH_MAX_WIDTH = 720; @@ -29,12 +29,14 @@ export const getAppbarHeight = ( return hasSubtitle ? 152 : 120; }; -export const getActionsWidth = (actions: readonly AppbarAction[]) => +export const getTrailingActionsWidth = ( + actions: readonly AppbarTrailingAction[] +) => actions.reduce( (width, action) => width + (action.variant !== 'standard' && action.width === 'wide' - ? APPBAR_WIDE_ACTION_SIZE - : APPBAR_ACTION_SIZE), + ? APPBAR_WIDE_ICON_BUTTON_SIZE + : APPBAR_ICON_BUTTON_SIZE), 0 ); diff --git a/src/components/__tests__/AppbarV3/AppbarV3.test.tsx b/src/components/__tests__/AppbarV3/AppbarV3.test.tsx index 287d449ed7..89bb874239 100644 --- a/src/components/__tests__/AppbarV3/AppbarV3.test.tsx +++ b/src/components/__tests__/AppbarV3/AppbarV3.test.tsx @@ -6,13 +6,13 @@ import { render, screen } from '../../../test-utils'; import AppbarV3 from '../../AppbarV3'; import type { AppbarVariant } from '../../AppbarV3'; -const writtenTitleVariants: Exclude[] = [ +const writtenHeadlineVariants: Exclude[] = [ 'small', 'medium-flexible', 'large-flexible', ]; -const decorativeTitleImage = ( +const decorativeHeadlineImage = ( @@ -22,21 +22,21 @@ const decorativeTitleImage = ( ); describe('AppbarV3 accessibility', () => { - it.each(writtenTitleVariants)( - 'exposes a written %s title as a heading', + it.each(writtenHeadlineVariants)( + 'exposes a written %s headline as a heading', async (variant) => { - await render(); + await render(); expect(screen.getByRole('heading', { name: 'Inbox' })).toBeOnTheScreen(); } ); - it('hides a small title image behind one named heading', async () => { + it('hides a small headline image behind one named heading', async () => { await render( ); @@ -47,13 +47,13 @@ describe('AppbarV3 accessibility', () => { }); it.each(['medium-flexible', 'large-flexible'] as const)( - 'does not expose duplicate content for a %s title image', + 'does not expose duplicate content for a %s headline image', async (variant) => { await render( ); @@ -63,24 +63,28 @@ describe('AppbarV3 accessibility', () => { } ); - it('exposes a pressable written title as a named button and heading', async () => { - const onTitlePress = jest.fn(); + it('exposes a pressable written headline as a named button and heading', async () => { + const onHeadlinePress = jest.fn(); await render( - + ); expect(screen.getByRole('button', { name: 'Inbox' })).toBeOnTheScreen(); expect(screen.getByRole('heading', { name: 'Inbox' })).toBeOnTheScreen(); }); - it('forwards custom title button accessibility props', async () => { + it('forwards custom headline button accessibility props', async () => { const onAccessibilityAction = jest.fn(); await render( {}} - titleActionProps={{ + headline="Inbox" + onHeadlinePress={() => {}} + headlinePressableProps={{ accessibilityActions: [{ name: 'activate', label: 'Open inbox' }], accessibilityHint: 'Opens the inbox menu', accessibilityLabel: 'Inbox options', @@ -113,20 +117,20 @@ describe('AppbarV3 accessibility', () => { ); }); - it('uses default and custom labels for back actions', async () => { + it('uses default and custom labels for back buttons', async () => { await render( ); @@ -137,12 +141,12 @@ describe('AppbarV3 accessibility', () => { ).toBeOnTheScreen(); }); - it('preserves icon action labels, hints, disabled state, and busy state', async () => { + it('preserves trailing action labels, hints, disabled state, and busy state', async () => { await render( { /> ); - const action = screen.getByRole('button', { + const trailingAction = screen.getByRole('button', { name: 'Save message', busy: true, disabled: true, }); - expect(action).toHaveProp('accessibilityHint', 'Saves the current draft'); - expect(action).toBeDisabled(); - expect(action).toBeBusy(); + expect(trailingAction).toHaveProp( + 'accessibilityHint', + 'Saves the current draft' + ); + expect(trailingAction).toBeDisabled(); + expect(trailingAction).toBeBusy(); }); it.each(['small', 'medium-flexible'] as const)( - 'hides decorative descendants of a %s title image', + 'hides decorative descendants of a %s headline image', async (variant) => { await render( variant === 'small' ? ( ) : ( ) ); - const imageContainer = screen.getByTestId('appbar-content-title-image', { - includeHiddenElements: true, - }); + const imageContainer = screen.getByTestId( + 'appbar-content-headline-image', + { includeHiddenElements: true } + ); expect(imageContainer).toHaveProp('aria-hidden', true); expect(imageContainer).toHaveProp( @@ -200,13 +208,13 @@ describe('AppbarV3 accessibility', () => { } ); - it('exposes leading, title, and trailing elements in source order', async () => { + it('exposes the leading button, headline, and trailing actions in source order', async () => { await render( { ]); }); - it('does not remount a surviving action when its configuration changes', async () => { + it('does not remount a surviving trailing action when its configuration changes', async () => { const { rerender } = await render( ); - const survivingAction = screen.getByRole('button', { + const survivingTrailingAction = screen.getByRole('button', { name: 'Keep action', }); await rerender( { ); expect(screen.getByRole('button', { name: 'Keep action' })).toBe( - survivingAction + survivingTrailingAction ); }); }); diff --git a/src/index.tsx b/src/index.tsx index 0f90db1c07..a7b8e58f80 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -63,16 +63,16 @@ export type { Props as AppbarContentProps } from './components/Appbar/AppbarCont export type { Props as AppbarHeaderProps } from './components/Appbar/AppbarHeader'; export type { Props as AppbarV3Props, - AppbarAction as AppbarV3Action, - AppbarActions as AppbarV3Actions, - AppbarFilledAction as AppbarV3FilledAction, - AppbarLeadingAction as AppbarV3LeadingAction, + AppbarFilledTrailingAction as AppbarV3FilledTrailingAction, + AppbarHeadlineAlignment as AppbarV3HeadlineAlignment, + AppbarHeadlinePressableProps as AppbarV3HeadlinePressableProps, + AppbarHeadlineTextProps as AppbarV3HeadlineTextProps, + AppbarLeadingButton as AppbarV3LeadingButton, AppbarSearchbarProps as AppbarV3SearchbarProps, - AppbarStandardAction as AppbarV3StandardAction, + AppbarStandardTrailingAction as AppbarV3StandardTrailingAction, AppbarTextProps as AppbarV3TextProps, - AppbarTitleActionProps as AppbarV3TitleActionProps, - AppbarTitleAlignment as AppbarV3TitleAlignment, - AppbarTitleTextProps as AppbarV3TitleTextProps, + AppbarTrailingAction as AppbarV3TrailingAction, + AppbarTrailingActions as AppbarV3TrailingActions, AppbarVariant as AppbarV3Variant, } from './components/AppbarV3'; export type { Props as AvatarIconProps } from './components/Avatar/AvatarIcon'; From 5b5c4a53dcb5d865a644d94c172d198e22598391 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Tue, 25 Aug 2026 11:03:30 +0200 Subject: [PATCH 18/20] test(appbar): appbar test suite --- .../__tests__/AppbarV3/AppbarV3.test.tsx | 433 +++++++++++++++++- .../__tests__/AppbarV3/utils.test.ts | 69 +++ 2 files changed, 501 insertions(+), 1 deletion(-) create mode 100644 src/components/__tests__/AppbarV3/utils.test.ts diff --git a/src/components/__tests__/AppbarV3/AppbarV3.test.tsx b/src/components/__tests__/AppbarV3/AppbarV3.test.tsx index 89bb874239..a86d3d1a8b 100644 --- a/src/components/__tests__/AppbarV3/AppbarV3.test.tsx +++ b/src/components/__tests__/AppbarV3/AppbarV3.test.tsx @@ -1,8 +1,11 @@ +import * as React from 'react'; import { Text, View } from 'react-native'; import { describe, expect, it, jest } from '@jest/globals'; +import { SafeAreaProvider } from 'react-native-safe-area-context'; -import { render, screen } from '../../../test-utils'; +import { getTheme } from '../../../core/theming'; +import { fireEvent, render, screen, userEvent } from '../../../test-utils'; import AppbarV3 from '../../AppbarV3'; import type { AppbarVariant } from '../../AppbarV3'; @@ -21,6 +24,401 @@ const decorativeHeadlineImage = ( ); +describe('AppbarV3 content', () => { + it.each([ + { + variant: 'small', + headlineVariant: 'titleLarge', + headlineLines: 1, + subtitleVariant: 'labelMedium', + subtitleSpacing: 0, + }, + { + variant: 'medium-flexible', + headlineVariant: 'headlineMedium', + headlineLines: 2, + subtitleVariant: 'labelLarge', + subtitleSpacing: 4, + }, + { + variant: 'large-flexible', + headlineVariant: 'displaySmall', + headlineLines: 2, + subtitleVariant: 'titleMedium', + subtitleSpacing: 8, + }, + ] as const)( + 'uses the $variant content treatment', + async ({ + variant, + headlineVariant, + headlineLines, + subtitleVariant, + subtitleSpacing, + }) => { + await render( + + ); + + expect(screen.getByTestId('appbar-content-headline-text')).toHaveStyle( + getTheme().fonts[headlineVariant] + ); + expect(screen.getByTestId('appbar-content-headline-text')).toHaveProp( + 'numberOfLines', + headlineLines + ); + expect(screen.getByTestId('appbar-content-subtitle-text')).toHaveStyle({ + ...getTheme().fonts[subtitleVariant], + color: getTheme().colors.onSurfaceVariant, + marginTop: subtitleSpacing, + }); + } + ); + + it('centers text and balances asymmetric controls for centered and image layouts', async () => { + const { rerender } = await render( + + ); + + expect(screen.getByTestId('appbar-content-headline-text')).toHaveStyle({ + textAlign: 'center', + }); + expect(screen.getByTestId('appbar-content-subtitle-text')).toHaveStyle({ + textAlign: 'center', + }); + expect( + screen.getByTestId('leading-action-container-outer-layer').parent + ).toHaveStyle({ width: 96 }); + expect( + screen.getByTestId('trailing-action-container-outer-layer').parent + ).toHaveStyle({ width: 96 }); + + await rerender( + } + leadingButton={{ + type: 'back', + testID: 'leading-action', + }} + trailingActions={[ + { + key: 'more', + icon: 'dots-vertical', + 'aria-label': 'More options', + testID: 'trailing-action', + }, + { + key: 'search', + icon: 'magnify', + 'aria-label': 'Search inbox', + }, + ]} + /> + ); + + expect( + screen.getByTestId('leading-action-container-outer-layer').parent + ).toHaveStyle({ width: 96 }); + expect( + screen.getByTestId('trailing-action-container-outer-layer').parent + ).toHaveStyle({ width: 96 }); + expect( + screen.getByTestId('brand-mark', { includeHiddenElements: true }) + ).toBeOnTheScreen(); + }); + + it('adjusts leading headline spacing when a leading button is present', async () => { + const { rerender } = await render( + + ); + + expect(screen.getByTestId('appbar-content')).toHaveStyle({ + marginStart: 12, + }); + + await rerender( + + ); + + expect(screen.getByTestId('appbar-content')).toHaveStyle({ + marginStart: 4, + }); + }); +}); + +describe('AppbarV3 surface', () => { + it('uses scroll container colors unless a custom background is supplied', async () => { + const customBackground = 'rebeccapurple'; + const { rerender } = await render( + + ); + + expect(screen.getByTestId('appbar-root-layer')).toHaveStyle({ + backgroundColor: getTheme().colors.surface, + }); + + await rerender(); + + expect(screen.getByTestId('appbar-root-layer')).toHaveStyle({ + backgroundColor: getTheme().colors.surfaceContainer, + }); + + await rerender( + + ); + + expect(screen.getByTestId('appbar-root-layer')).toHaveStyle({ + backgroundColor: customBackground, + }); + }); + + it('applies border clipping and resolves safe-area overrides on the surface', async () => { + await render( + + + + ); + + expect(screen.getByTestId('appbar-root-layer')).toHaveStyle({ + borderBottomLeftRadius: 16, + borderBottomRightRadius: 16, + paddingTop: 20, + paddingHorizontal: 12, + }); + }); +}); + +describe('AppbarV3 actions', () => { + it('maps leading, trailing, and custom action colors', async () => { + await render( + ( + + ), + 'aria-label': 'Navigation', + }} + trailingActions={[ + { + key: 'default', + icon: ({ color }) => ( + + ), + 'aria-label': 'Default action', + }, + { + key: 'custom', + icon: ({ color }) => ( + + ), + 'aria-label': 'Custom action', + color: 'rebeccapurple', + }, + ]} + /> + ); + + expect(screen.getByTestId('leading-icon-color')).toHaveStyle({ + backgroundColor: getTheme().colors.onSurface, + }); + expect(screen.getByTestId('trailing-icon-color')).toHaveStyle({ + backgroundColor: getTheme().colors.onSurfaceVariant, + }); + expect(screen.getByTestId('custom-icon-color')).toHaveStyle({ + backgroundColor: 'rebeccapurple', + }); + }); + + it.each([ + { variant: 'filled', color: getTheme().colors.primary }, + { variant: 'tonal', color: getTheme().colors.secondaryContainer }, + ] as const)( + 'maps $variant actions to their selected container color', + async ({ variant, color }) => { + await render( + + ); + + expect(screen.getByTestId('expressive-action-container')).toHaveStyle({ + backgroundColor: color, + }); + expect( + screen.getByTestId('expressive-action-container-outer-layer') + ).toHaveStyle({ width: 56 }); + } + ); +}); + +describe('AppbarV3 search', () => { + it('uses the placeholder as the searchbox label unless an explicit label is supplied', async () => { + const { rerender } = await render( + + ); + + expect( + screen.getByRole('searchbox', { name: 'Search messages' }) + ).toBeOnTheScreen(); + expect(screen.getByTestId('appbar-search-container')).toHaveStyle({ + backgroundColor: getTheme().colors.surfaceContainer, + }); + + await rerender( + + ); + + expect( + screen.getByRole('searchbox', { name: 'Message search' }) + ).toBeOnTheScreen(); + }); + + it('configures the search field, forwards its behavior, and constrains its measured width', async () => { + const onChangeText = jest.fn(); + const SearchAppbar = () => { + const [value, setValue] = React.useState(''); + + return ( + { + setValue(nextValue); + onChangeText(nextValue); + }, + testID: 'message-search', + }} + trailingActions={[ + { + key: 'more', + icon: 'dots-vertical', + 'aria-label': 'More options', + }, + ]} + /> + ); + }; + + await render(); + + const searchbox = screen.getByRole('searchbox', { + name: 'Search messages', + }); + expect(searchbox).toHaveStyle({ + color: getTheme().colors.onSurface, + textAlign: 'center', + }); + expect(searchbox).toHaveProp( + 'placeholderTextColor', + getTheme().colors.onSurfaceVariant + ); + expect(screen.getByTestId('message-search-container')).toHaveStyle({ + backgroundColor: getTheme().colors.surfaceContainerHighest, + }); + expect( + screen.getByRole('button', { name: 'Navigate back' }) + ).toBeOnTheScreen(); + expect( + screen.getByRole('button', { name: 'More options' }) + ).toBeOnTheScreen(); + + await userEvent.type(searchbox, 'draft'); + expect(onChangeText).toHaveBeenLastCalledWith('draft'); + expect(searchbox).toHaveProp('value', 'draft'); + + await fireEvent(screen.getByTestId('appbar-search-slot'), 'layout', { + nativeEvent: { layout: { x: 0, y: 0, width: 800, height: 56 } }, + }); + + expect( + screen.getByTestId('message-search-container-outer-layer') + ).toHaveStyle({ width: 720 }); + }); +}); + describe('AppbarV3 accessibility', () => { it.each(writtenHeadlineVariants)( 'exposes a written %s headline as a heading', @@ -77,6 +475,39 @@ describe('AppbarV3 accessibility', () => { expect(screen.getByRole('heading', { name: 'Inbox' })).toBeOnTheScreen(); }); + it('does not invoke a disabled headline action', async () => { + const onHeadlinePress = jest.fn(); + await render( + + ); + + const headlineButton = screen.getByRole('button', { + name: 'Inbox', + disabled: true, + }); + await userEvent.press(headlineButton); + + expect(onHeadlinePress).not.toHaveBeenCalled(); + }); + + it('names a pressable small headline image from its fallback headline', async () => { + await render( + {}} + /> + ); + + expect(screen.getByRole('button', { name: 'Inbox' })).toBeOnTheScreen(); + }); + it('forwards custom headline button accessibility props', async () => { const onAccessibilityAction = jest.fn(); await render( diff --git a/src/components/__tests__/AppbarV3/utils.test.ts b/src/components/__tests__/AppbarV3/utils.test.ts new file mode 100644 index 0000000000..b3f0ee8e94 --- /dev/null +++ b/src/components/__tests__/AppbarV3/utils.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from '@jest/globals'; + +import { + getAppbarHeight, + getAppbarSearchWidth, + getTrailingActionsWidth, +} from '../../AppbarV3/utils'; + +describe('getAppbarHeight', () => { + it.each([ + { variant: 'search', subtitle: false, height: 64 }, + { variant: 'search', subtitle: true, height: 64 }, + { variant: 'small', subtitle: false, height: 64 }, + { variant: 'small', subtitle: true, height: 64 }, + { variant: 'medium-flexible', subtitle: false, height: 112 }, + { variant: 'medium-flexible', subtitle: true, height: 136 }, + { variant: 'large-flexible', subtitle: false, height: 120 }, + { variant: 'large-flexible', subtitle: true, height: 152 }, + ] as const)( + 'returns $height for $variant with subtitle=$subtitle', + ({ variant, subtitle, height }) => { + expect(getAppbarHeight(variant, subtitle)).toBe(height); + } + ); +}); + +describe('getAppbarSearchWidth', () => { + it.each([ + [320, 320], + [360, 360], + [600, 600], + [800, 720], + ])('constrains %i available pixels to %i', (availableWidth, width) => { + expect(getAppbarSearchWidth(availableWidth)).toBe(width); + }); +}); + +describe('getTrailingActionsWidth', () => { + it('accounts for standard, filled, and wide filled actions', () => { + expect(getTrailingActionsWidth([])).toBe(0); + expect( + getTrailingActionsWidth([ + { key: 'first', icon: 'star', 'aria-label': 'First' }, + { key: 'second', icon: 'heart', 'aria-label': 'Second' }, + ]) + ).toBe(96); + expect( + getTrailingActionsWidth([ + { + key: 'filled', + icon: 'star', + 'aria-label': 'Filled', + variant: 'filled', + }, + ]) + ).toBe(48); + expect( + getTrailingActionsWidth([ + { + key: 'wide', + icon: 'star', + 'aria-label': 'Wide', + variant: 'tonal', + width: 'wide', + }, + ]) + ).toBe(64); + }); +}); From ae3553849b3b1d1374daa72a86b55c4ecc7679b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Tue, 25 Aug 2026 12:01:18 +0200 Subject: [PATCH 19/20] refactor(appbar): optimizations --- src/components/AppbarV3/Appbar.tsx | 198 +++++++++--------- src/components/AppbarV3/AppbarButton.tsx | 38 +++- src/components/AppbarV3/AppbarContent.tsx | 55 +++-- src/components/AppbarV3/utils.ts | 9 - .../__tests__/AppbarV3/AppbarV3.test.tsx | 41 +++- .../__tests__/AppbarV3/utils.test.ts | 17 +- 6 files changed, 204 insertions(+), 154 deletions(-) diff --git a/src/components/AppbarV3/Appbar.tsx b/src/components/AppbarV3/Appbar.tsx index b663f852b7..4d756ca44f 100644 --- a/src/components/AppbarV3/Appbar.tsx +++ b/src/components/AppbarV3/Appbar.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; import { StyleSheet, View } from 'react-native'; -import type { ColorValue, LayoutChangeEvent, ViewProps } from 'react-native'; +import type { ColorValue, ViewProps } from 'react-native'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; @@ -10,8 +10,8 @@ import type { Props } from './types'; import { APPBAR_HEADLINE_IMAGE_HEIGHT, APPBAR_ICON_BUTTON_SIZE, + APPBAR_SEARCH_MAX_WIDTH, getAppbarHeight, - getAppbarSearchWidth, getTrailingActionsWidth, } from './utils'; import { useInternalTheme } from '../../core/theming'; @@ -19,6 +19,8 @@ import { getAppbarBorders } from '../Appbar/utils'; import Searchbar from '../Searchbar'; import Surface from '../Surface'; +const EMPTY_TRAILING_ACTIONS = [] as const; + const Appbar = ({ contentStyle, headline, @@ -37,23 +39,30 @@ const Appbar = ({ subtitleProps, testID = 'appbar', theme: themeOverrides, - trailingActions = [], + trailingActions = EMPTY_TRAILING_ACTIONS, variant, ref, ...rest }: Props) => { const theme = useInternalTheme(themeOverrides); const detectedInsets = useSafeAreaInsets(); - const [searchSlotWidth, setSearchSlotWidth] = React.useState(0); - const flattenedStyle = StyleSheet.flatten(style); - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - const resolvedStyle = (flattenedStyle || {}) as Exclude< - typeof flattenedStyle, - number - > & { - backgroundColor?: ColorValue; - }; - const { backgroundColor: customBackground, ...restStyle } = resolvedStyle; + const { customBackground, restStyle, borderRadius } = React.useMemo(() => { + const flattenedStyle = StyleSheet.flatten(style); + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + const resolvedStyle = (flattenedStyle || {}) as Exclude< + typeof flattenedStyle, + number + > & { + backgroundColor?: ColorValue; + }; + const { backgroundColor, ...remainingStyle } = resolvedStyle; + + return { + customBackground: backgroundColor, + restStyle: remainingStyle, + borderRadius: getAppbarBorders(remainingStyle), + }; + }, [style]); const backgroundColor = customBackground ?? (isScrolled ? theme.colors.surfaceContainer : theme.colors.surface); @@ -63,8 +72,46 @@ const Appbar = ({ const leftInset = safeAreaInsets?.left ?? detectedInsets.left; const rightInset = safeAreaInsets?.right ?? detectedInsets.right; const horizontalInset = Math.max(leftInset, rightInset); - const borderRadius = getAppbarBorders(restStyle); const centered = headlineAlignment === 'center'; + const sideWidth = Math.max( + leadingButton ? APPBAR_ICON_BUTTON_SIZE : 0, + getTrailingActionsWidth(trailingActions) + ); + const sideStyle = React.useMemo(() => ({ width: sideWidth }), [sideWidth]); + const surfaceStyle = React.useMemo( + () => [ + { + backgroundColor, + paddingTop: topInset, + paddingHorizontal: horizontalInset, + }, + borderRadius, + ], + [backgroundColor, borderRadius, horizontalInset, topInset] + ); + const appbarStyle = React.useMemo( + () => [styles.appbar, { backgroundColor, minHeight }, restStyle], + [backgroundColor, minHeight, restStyle] + ); + const resolvedSearchInputStyle = React.useMemo( + () => [ + searchBar?.inputStyle, + styles.searchInput, + { color: theme.colors.onSurface }, + ], + [searchBar?.inputStyle, theme.colors.onSurface] + ); + const searchBackgroundColor = isScrolled + ? theme.colors.surfaceContainerHighest + : theme.colors.surfaceContainer; + const resolvedSearchStyle = React.useMemo( + () => [ + styles.searchBar, + { backgroundColor: searchBackgroundColor }, + searchBar?.style, + ], + [searchBackgroundColor, searchBar?.style] + ); const { accessibilityLabel: _accessibilityLabel, accessibilityRole: _accessibilityRole, @@ -74,17 +121,6 @@ const Appbar = ({ ...viewProps } = rest as ViewProps; - const handleSearchSlotLayout = React.useCallback( - ({ nativeEvent }: LayoutChangeEvent) => { - const nextWidth = nativeEvent.layout.width; - - setSearchSlotWidth((currentWidth) => - currentWidth === nextWidth ? currentWidth : nextWidth - ); - }, - [] - ); - const renderLeadingButton = () => leadingButton ? ( @@ -101,48 +137,35 @@ const Appbar = ({ } const { - inputStyle: searchInputStyle, - style: searchStyle, + inputStyle: _searchInputStyle, + style: _searchStyle, testID: searchTestID = `${testID}-search`, ...searchProps } = searchBar; - const searchWidth = searchSlotWidth - ? getAppbarSearchWidth(searchSlotWidth) - : '100%'; - const searchBackgroundColor = isScrolled - ? theme.colors.surfaceContainerHighest - : theme.colors.surfaceContainer; return ( {renderLeadingButton()} - - + + + + {renderTrailingActions()} @@ -185,20 +208,11 @@ const Appbar = ({ } if (centered || headlineImage) { - const sideWidth = Math.max( - leadingButton ? APPBAR_ICON_BUTTON_SIZE : 0, - getTrailingActionsWidth(trailingActions) - ); - return ( - - {renderLeadingButton()} - + {renderLeadingButton()} - + {renderTrailingActions()} @@ -224,26 +238,15 @@ const Appbar = ({ return null; } - const sideWidth = Math.max( - leadingButton ? APPBAR_ICON_BUTTON_SIZE : 0, - getTrailingActionsWidth(trailingActions) - ); - return ( {headlineImage ? ( - + {renderLeadingButton()} {renderFlexibleHeadlineImage()} - + {renderTrailingActions()} @@ -267,20 +270,9 @@ const Appbar = ({ elevation={0} container theme={theme} - style={[ - { - backgroundColor, - paddingTop: topInset, - paddingHorizontal: horizontalInset, - }, - borderRadius, - ]} + style={surfaceStyle} > - + {variant === 'search' ? renderSearchAppbar() : variant === 'small' @@ -311,7 +303,11 @@ const styles = StyleSheet.create({ alignItems: 'center', }, searchBar: { - maxWidth: '100%', + width: '100%', + }, + searchWidthLimiter: { + width: '100%', + maxWidth: APPBAR_SEARCH_MAX_WIDTH, }, searchInput: { textAlign: 'center', @@ -349,7 +345,9 @@ const styles = StyleSheet.create({ }, }); -export default Appbar; +const MemoizedAppbar = React.memo(Appbar); + +export default MemoizedAppbar; // @component-docs ignore-next-line -export { Appbar }; +export { MemoizedAppbar as Appbar }; diff --git a/src/components/AppbarV3/AppbarButton.tsx b/src/components/AppbarV3/AppbarButton.tsx index 251190aa91..b6e7d942aa 100644 --- a/src/components/AppbarV3/AppbarButton.tsx +++ b/src/components/AppbarV3/AppbarButton.tsx @@ -1,3 +1,4 @@ +import * as React from 'react'; import { StyleSheet } from 'react-native'; import type { AppbarLeadingButton, AppbarTrailingAction } from './types'; @@ -56,6 +57,41 @@ const AppbarButton = ({ button, leading = false, theme }: Props) => { ); }; +const hasEqualButtonProps = ( + previous: Props['button'], + next: Props['button'] +) => { + if (previous === next) { + return true; + } + + const previousKeys = Object.keys(previous); + const nextKeys = Object.keys(next); + + if (previousKeys.length !== nextKeys.length) { + return false; + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + const previousRecord = previous as unknown as Record; + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + const nextRecord = next as unknown as Record; + + return previousKeys.every( + (key) => + Object.prototype.hasOwnProperty.call(nextRecord, key) && + Object.is(previousRecord[key], nextRecord[key]) + ); +}; + +const MemoizedAppbarButton = React.memo( + AppbarButton, + (previous, next) => + previous.leading === next.leading && + previous.theme === next.theme && + hasEqualButtonProps(previous.button, next.button) +); + const styles = StyleSheet.create({ button: { margin: 4, @@ -65,4 +101,4 @@ const styles = StyleSheet.create({ }, }); -export default AppbarButton; +export default MemoizedAppbarButton; diff --git a/src/components/AppbarV3/AppbarContent.tsx b/src/components/AppbarV3/AppbarContent.tsx index bba1db657e..ecc54513ae 100644 --- a/src/components/AppbarV3/AppbarContent.tsx +++ b/src/components/AppbarV3/AppbarContent.tsx @@ -1,3 +1,4 @@ +import * as React from 'react'; import { Pressable, StyleSheet, View } from 'react-native'; import type { StyleProp, ViewStyle } from 'react-native'; @@ -65,6 +66,35 @@ const AppbarContent = ({ const subtitleVariant = subtitleVariants[variant]; const centered = alignment === 'center'; const hasHeadlineImage = variant === 'small' && Boolean(headlineImage); + const headlineStyle = React.useMemo( + () => [ + styles.text, + centered && styles.centeredText, + { color: theme.colors.onSurface }, + headlineProps?.style, + ], + [centered, headlineProps?.style, theme.colors.onSurface] + ); + const subtitleStyle = React.useMemo( + () => [ + styles.text, + centered && styles.centeredText, + { marginTop: subtitleSpacing[variant] }, + { color: theme.colors.onSurfaceVariant }, + subtitleProps?.style, + ], + [centered, subtitleProps?.style, theme.colors.onSurfaceVariant, variant] + ); + const wrapperStyle = React.useMemo( + () => [ + styles.container, + variant !== 'small' && styles.flexibleContainer, + centered && styles.centeredContainer, + style, + contentStyle, + ], + [centered, contentStyle, style, variant] + ); const content = hasHeadlineImage ? ( {headline} @@ -102,13 +127,7 @@ const AppbarContent = ({ numberOfLines={1} maxFontSizeMultiplier={subtitleProps?.maxFontSizeMultiplier} testID={`${testID}-subtitle-text`} - style={[ - styles.text, - centered && styles.centeredText, - { marginTop: subtitleSpacing[variant] }, - { color: theme.colors.onSurfaceVariant }, - subtitleProps?.style, - ]} + style={subtitleStyle} > {subtitle} @@ -118,13 +137,7 @@ const AppbarContent = ({ const wrapperProps = { testID, - style: [ - styles.container, - variant !== 'small' && styles.flexibleContainer, - centered && styles.centeredContainer, - style, - contentStyle, - ], + style: wrapperStyle, }; if (onHeadlinePress) { @@ -200,4 +213,4 @@ const styles = StyleSheet.create({ }, }); -export default AppbarContent; +export default React.memo(AppbarContent); diff --git a/src/components/AppbarV3/utils.ts b/src/components/AppbarV3/utils.ts index 6ab0c7b02f..4677ffc43c 100644 --- a/src/components/AppbarV3/utils.ts +++ b/src/components/AppbarV3/utils.ts @@ -3,17 +3,8 @@ import type { AppbarTrailingAction, AppbarVariant } from './types'; export const APPBAR_ICON_BUTTON_SIZE = 48; export const APPBAR_WIDE_ICON_BUTTON_SIZE = 64; export const APPBAR_HEADLINE_IMAGE_HEIGHT = 32; -export const APPBAR_SEARCH_MIN_WIDTH = 360; export const APPBAR_SEARCH_MAX_WIDTH = 720; -export const getAppbarSearchWidth = (availableWidth: number) => { - if (availableWidth < APPBAR_SEARCH_MIN_WIDTH) { - return availableWidth; - } - - return Math.min(availableWidth, APPBAR_SEARCH_MAX_WIDTH); -}; - export const getAppbarHeight = ( variant: AppbarVariant, hasSubtitle: boolean diff --git a/src/components/__tests__/AppbarV3/AppbarV3.test.tsx b/src/components/__tests__/AppbarV3/AppbarV3.test.tsx index a86d3d1a8b..fc0ceb397b 100644 --- a/src/components/__tests__/AppbarV3/AppbarV3.test.tsx +++ b/src/components/__tests__/AppbarV3/AppbarV3.test.tsx @@ -5,7 +5,7 @@ import { describe, expect, it, jest } from '@jest/globals'; import { SafeAreaProvider } from 'react-native-safe-area-context'; import { getTheme } from '../../../core/theming'; -import { fireEvent, render, screen, userEvent } from '../../../test-utils'; +import { render, screen, userEvent } from '../../../test-utils'; import AppbarV3 from '../../AppbarV3'; import type { AppbarVariant } from '../../AppbarV3'; @@ -236,6 +236,33 @@ describe('AppbarV3 surface', () => { }); describe('AppbarV3 actions', () => { + it('skips rendering unchanged action configurations', async () => { + const icon = jest.fn(() => ); + const { rerender } = await render( + + ); + const initialRenderCount = icon.mock.calls.length; + + await rerender( + + ); + + expect(screen.getByTestId('stable-action-icon')).toBeOnTheScreen(); + expect(icon).toHaveBeenCalledTimes(initialRenderCount); + }); + it('maps leading, trailing, and custom action colors', async () => { await render( { ).toBeOnTheScreen(); }); - it('configures the search field, forwards its behavior, and constrains its measured width', async () => { + it('configures the search field, forwards its behavior, and constrains its width', async () => { const onChangeText = jest.fn(); const SearchAppbar = () => { const [value, setValue] = React.useState(''); @@ -409,13 +436,13 @@ describe('AppbarV3 search', () => { expect(onChangeText).toHaveBeenLastCalledWith('draft'); expect(searchbox).toHaveProp('value', 'draft'); - await fireEvent(screen.getByTestId('appbar-search-slot'), 'layout', { - nativeEvent: { layout: { x: 0, y: 0, width: 800, height: 56 } }, - }); - expect( screen.getByTestId('message-search-container-outer-layer') - ).toHaveStyle({ width: 720 }); + ).toHaveStyle({ width: '100%' }); + expect(screen.getByTestId('appbar-search-width-limiter')).toHaveStyle({ + width: '100%', + maxWidth: 720, + }); }); }); diff --git a/src/components/__tests__/AppbarV3/utils.test.ts b/src/components/__tests__/AppbarV3/utils.test.ts index b3f0ee8e94..d37a585372 100644 --- a/src/components/__tests__/AppbarV3/utils.test.ts +++ b/src/components/__tests__/AppbarV3/utils.test.ts @@ -1,10 +1,6 @@ import { describe, expect, it } from '@jest/globals'; -import { - getAppbarHeight, - getAppbarSearchWidth, - getTrailingActionsWidth, -} from '../../AppbarV3/utils'; +import { getAppbarHeight, getTrailingActionsWidth } from '../../AppbarV3/utils'; describe('getAppbarHeight', () => { it.each([ @@ -24,17 +20,6 @@ describe('getAppbarHeight', () => { ); }); -describe('getAppbarSearchWidth', () => { - it.each([ - [320, 320], - [360, 360], - [600, 600], - [800, 720], - ])('constrains %i available pixels to %i', (availableWidth, width) => { - expect(getAppbarSearchWidth(availableWidth)).toBe(width); - }); -}); - describe('getTrailingActionsWidth', () => { it('accounts for standard, filled, and wide filled actions', () => { expect(getTrailingActionsWidth([])).toBe(0); From 19b043ad318f9efb098faf7542a10a5d317eb481 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Kata?= Date: Tue, 25 Aug 2026 12:42:12 +0200 Subject: [PATCH 20/20] feat(appbar): replace v2 with v3 + docs + example app update --- docs/6.x/docs/components/Appbar/Appbar.mdx | 199 ++-- .../docs/components/Appbar/AppbarAction.mdx | 134 --- .../components/Appbar/AppbarBackAction.mdx | 101 -- .../docs/components/Appbar/AppbarContent.mdx | 129 --- .../docs/components/Appbar/AppbarHeader.mdx | 125 --- docs/6.x/docs/components/Appbar/_meta.json | 6 +- docs/6.x/docs/guides/react-navigation.md | 65 +- .../guides/theming-with-react-navigation.md | 23 +- docs/6.x/docs/guides/theming.mdx | 6 +- docs/component-docs.config.ts | 4 - docs/src/data/componentDocs6x.json | 610 +---------- docs/src/data/screenshots.ts | 10 - docs/src/data/themeColors.ts | 23 +- example/src/ExampleList.tsx | 2 - example/src/Examples/AppbarExample.tsx | 453 ++++++-- example/src/Examples/AppbarV3Example.tsx | 456 -------- .../src/Examples/BottomNavigationExample.tsx | 86 +- example/src/Examples/MenuExample.tsx | 57 +- example/src/Examples/TeamDetails.tsx | 13 +- example/src/Examples/TooltipExample.tsx | 45 +- example/src/RootNavigator.tsx | 26 +- src/components/Appbar/Appbar.tsx | 641 +++++++----- src/components/Appbar/AppbarAction.tsx | 117 --- src/components/Appbar/AppbarBackAction.tsx | 79 -- .../{AppbarV3 => Appbar}/AppbarButton.tsx | 2 +- src/components/Appbar/AppbarContent.tsx | 368 ++++--- src/components/Appbar/AppbarHeader.tsx | 164 --- src/components/Appbar/index.ts | 38 +- src/components/{AppbarV3 => Appbar}/types.ts | 0 src/components/Appbar/utils.ts | 191 +--- src/components/AppbarV3/Appbar.tsx | 353 ------- src/components/AppbarV3/AppbarContent.tsx | 216 ---- src/components/AppbarV3/index.ts | 16 - src/components/AppbarV3/utils.ts | 33 - .../__tests__/Appbar/Appbar.test.tsx | 985 +++++++++++------- .../Appbar/__snapshots__/Appbar.test.tsx.snap | 881 ---------------- .../{AppbarV3 => Appbar}/utils.test.ts | 2 +- .../__tests__/AppbarV3/AppbarV3.test.tsx | 725 ------------- src/index.tsx | 32 +- 39 files changed, 1872 insertions(+), 5544 deletions(-) delete mode 100644 docs/6.x/docs/components/Appbar/AppbarAction.mdx delete mode 100644 docs/6.x/docs/components/Appbar/AppbarBackAction.mdx delete mode 100644 docs/6.x/docs/components/Appbar/AppbarContent.mdx delete mode 100644 docs/6.x/docs/components/Appbar/AppbarHeader.mdx delete mode 100644 example/src/Examples/AppbarV3Example.tsx delete mode 100644 src/components/Appbar/AppbarAction.tsx delete mode 100644 src/components/Appbar/AppbarBackAction.tsx rename src/components/{AppbarV3 => Appbar}/AppbarButton.tsx (97%) delete mode 100644 src/components/Appbar/AppbarHeader.tsx rename src/components/{AppbarV3 => Appbar}/types.ts (100%) delete mode 100644 src/components/AppbarV3/Appbar.tsx delete mode 100644 src/components/AppbarV3/AppbarContent.tsx delete mode 100644 src/components/AppbarV3/index.ts delete mode 100644 src/components/AppbarV3/utils.ts delete mode 100644 src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap rename src/components/__tests__/{AppbarV3 => Appbar}/utils.test.ts (98%) delete mode 100644 src/components/__tests__/AppbarV3/AppbarV3.test.tsx diff --git a/docs/6.x/docs/components/Appbar/Appbar.mdx b/docs/6.x/docs/components/Appbar/Appbar.mdx index 798b6dd136..0338f367ff 100644 --- a/docs/6.x/docs/components/Appbar/Appbar.mdx +++ b/docs/6.x/docs/components/Appbar/Appbar.mdx @@ -8,95 +8,100 @@ import ThemeColorsTable from '@docs/components/ThemeColorsTable.tsx'; import ScreenshotTabs from '@docs/components/ScreenshotTabs.tsx'; import ExtendedExample from '@docs/components/ExtendedExample.tsx'; -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. - -By default Appbar uses primary color as a background, in dark theme with `adaptive` mode it will use surface colour instead. -See [Dark Theme](https://callstack.github.io/react-native-paper/docs/guides/theming#dark-theme) for more informations - - - - - - - +A Material Design app bar for displaying a page headline, navigation, and +contextual actions. Appbar supports small, medium flexible, large flexible, +and search variants. Its surface color automatically changes when content +has scrolled, and it accounts for safe-area insets. + +## Variants + +| `variant` | Purpose | +| --- | --- | +| `small` | A compact 64dp app bar with a one-line headline. | +| `medium-flexible` | A flexible app bar with a two-line headline and optional subtitle or image. | +| `large-flexible` | A prominent flexible app bar with a two-line headline and optional subtitle or image. | +| `search` | An app bar containing a centered Paper `Searchbar`. | + +## Main props + +| Prop | Description | +| --- | --- | +| `headline` | Required accessible headline for every non-search variant. | +| `subtitle` | Optional supporting text for written headlines. | +| `headlineAlignment` | Aligns headline content to `leading` (default) or `center`. | +| `headlineImage` | Replaces the visible small headline, or appears above a flexible headline. Images should fit within 32dp height. | +| `onHeadlinePress` | Makes the headline area interactive; use `headlinePressableProps` for its accessibility state. | +| `leadingButton` | A back button (`{ type: 'back' }`) or standard icon-button configuration. | +| `trailingActions` | Standard icon-button configurations, or exactly one `filled`/`tonal` action with optional `wide` width. Every action requires a stable `key` and `aria-label`. | +| `searchBar` | Required for the `search` variant. Accepts Paper `Searchbar` props except `mode`, `elevation`, `showDivider`, and `theme`. | +| `isScrolled` | Uses `surfaceContainer` instead of `surface` when content has scrolled. | +| `safeAreaInsets` | Overrides detected top, left, or right safe-area insets. | +| `statusBarHeight` | Overrides only the automatic top inset. | +| `contentStyle` | Styles the headline and subtitle area. | +| `style` | Styles the app bar and can override its background color. | + +## Migrating from the compound API + +`Appbar.Header`, `Appbar.Content`, `Appbar.Action`, and +`Appbar.BackAction` have been removed. Render one `Appbar` and provide its +headline, leading button, and trailing actions as props. The former +`mode="medium"` and `mode="large"` values are now +`variant="medium-flexible"` and `variant="large-flexible"`; centered +content uses `headlineAlignment="center"`. ## Usage -### Top bar + +### Small app bar ```js import * as React from 'react'; import { Appbar } from 'react-native-paper'; const MyComponent = () => ( - - {}} /> - - {}} /> - {}} /> - + {} }} + trailingActions={[ + { + key: 'search', + icon: 'magnify', + 'aria-label': 'Search', + onPress: () => {}, + }, + { + key: 'more', + icon: 'dots-vertical', + 'aria-label': 'More options', + onPress: () => {}, + }, + ]} + /> ); export default MyComponent; ``` -### Bottom bar +### Flexible app bar ```js -import * as React from 'react'; -import { StyleSheet } from 'react-native'; -import { Appbar, FAB, useTheme } from 'react-native-paper'; -import { useSafeAreaInsets } from 'react-native-safe-area-context'; - -const BOTTOM_APPBAR_HEIGHT = 80; -const MEDIUM_FAB_HEIGHT = 56; - -const MyComponent = () => { - const { bottom } = useSafeAreaInsets(); - const theme = useTheme(); - - return ( - - {}} /> - {}} /> - {}} /> - {}} /> - {}} - style={[ - styles.fab, - { top: (BOTTOM_APPBAR_HEIGHT - MEDIUM_FAB_HEIGHT) / 2 }, - ]} - /> - - ); -}; - -const styles = StyleSheet.create({ - bottom: { - backgroundColor: 'aquamarine', - position: 'absolute', - left: 0, - right: 0, - bottom: 0, - }, - fab: { - position: 'absolute', - right: 16, - }, -}); + +``` -export default MyComponent; +### Search app bar +```js + {} }} + searchBar={{ + placeholder: 'Search messages', + value: query, + onChangeText: setQuery, + }} +/> ``` @@ -107,59 +112,35 @@ export default MyComponent;
-### dark - -
- - - -
- -### children (required) - -
- - - -
- -### mode Available in v5.x with theme version 3 - -
- - - -
- -### elevated Available in v5.x with theme version 3 +### headlineAlignment
- +
-### safeAreaInsets +### isScrolled
- +
-### theme +### testID
- +
-### style +### trailingActions
- + @@ -168,7 +149,7 @@ export default MyComponent; ## Theme colors - + diff --git a/docs/6.x/docs/components/Appbar/AppbarAction.mdx b/docs/6.x/docs/components/Appbar/AppbarAction.mdx deleted file mode 100644 index 5db23d4ba9..0000000000 --- a/docs/6.x/docs/components/Appbar/AppbarAction.mdx +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Appbar.Action ---- - -import PropTable from '@docs/components/PropTable.tsx'; -import ExtendsLink from '@docs/components/ExtendsLink.tsx'; -import ThemeColorsTable from '@docs/components/ThemeColorsTable.tsx'; -import ScreenshotTabs from '@docs/components/ScreenshotTabs.tsx'; -import ExtendedExample from '@docs/components/ExtendedExample.tsx'; - -A component used to display an action item in the appbar. - - - - - - - -## Usage -```js -import * as React from 'react'; -import { Appbar } from 'react-native-paper'; -import { Platform } from 'react-native'; - -const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical'; - -const MyComponent = () => ( - - - {}} /> - {}} /> - -); - -export default MyComponent; -``` - - - ## Props - - - - -
- -### color - -
- - - -
- -### icon (required) - -
- - - -
- -### size - -
- - - -
- -### disabled - -
- - - -
- -### aria-label - -
- - - -
- -### onPress - -
- - - -
- -### isLeading Available in v5.x with theme version 3 - -
- - - -
- -### style - -
- - - -
- -### ref - -
- - - -
- -### theme - -
- - - - - - - - - ## Theme colors - - - - - diff --git a/docs/6.x/docs/components/Appbar/AppbarBackAction.mdx b/docs/6.x/docs/components/Appbar/AppbarBackAction.mdx deleted file mode 100644 index 4faa4ec18d..0000000000 --- a/docs/6.x/docs/components/Appbar/AppbarBackAction.mdx +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Appbar.BackAction ---- - -import PropTable from '@docs/components/PropTable.tsx'; -import ExtendsLink from '@docs/components/ExtendsLink.tsx'; -import ThemeColorsTable from '@docs/components/ThemeColorsTable.tsx'; -import ScreenshotTabs from '@docs/components/ScreenshotTabs.tsx'; -import ExtendedExample from '@docs/components/ExtendedExample.tsx'; - -A component used to display a back button in the appbar. - - - - - - - -## Usage -```js -import * as React from 'react'; -import { Appbar } from 'react-native-paper'; - -const MyComponent = () => ( - - {}} /> - -); - -export default MyComponent; -``` - - - ## Props - - - - -
- -### color - -
- - - -
- -### size - -
- - - -
- -### disabled - -
- - - -
- -### aria-label - -
- - - -
- -### onPress - -
- - - -
- -### style - -
- - - -
- -### ref - -
- - - - - - - - - - diff --git a/docs/6.x/docs/components/Appbar/AppbarContent.mdx b/docs/6.x/docs/components/Appbar/AppbarContent.mdx deleted file mode 100644 index a3c4953c66..0000000000 --- a/docs/6.x/docs/components/Appbar/AppbarContent.mdx +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Appbar.Content ---- - -import PropTable from '@docs/components/PropTable.tsx'; -import ExtendsLink from '@docs/components/ExtendsLink.tsx'; -import ThemeColorsTable from '@docs/components/ThemeColorsTable.tsx'; -import ScreenshotTabs from '@docs/components/ScreenshotTabs.tsx'; -import ExtendedExample from '@docs/components/ExtendedExample.tsx'; - -A component used to display a title in an appbar. - - - - - - - -## Usage -```js -import * as React from 'react'; -import { Appbar } from 'react-native-paper'; - -const MyComponent = () => ( - - - -); - -export default MyComponent; -``` - - - ## Props - - - - -
- -### title (required) - -
- - - -
- -### titleStyle - -
- - - -
- -### titleRef - -
- - - -
- -### onPress - -
- - - -
- -### disabled - -
- - - -
- -### color - -
- - - -
- -### titleMaxFontSizeMultiplier - -
- - - -
- -### style - -
- - - -
- -### theme - -
- - - -
- -### testID - -
- - - - - - - - - ## Theme colors - - - - - diff --git a/docs/6.x/docs/components/Appbar/AppbarHeader.mdx b/docs/6.x/docs/components/Appbar/AppbarHeader.mdx deleted file mode 100644 index f541042a00..0000000000 --- a/docs/6.x/docs/components/Appbar/AppbarHeader.mdx +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Appbar.Header ---- - -import PropTable from '@docs/components/PropTable.tsx'; -import ExtendsLink from '@docs/components/ExtendsLink.tsx'; -import ThemeColorsTable from '@docs/components/ThemeColorsTable.tsx'; -import ScreenshotTabs from '@docs/components/ScreenshotTabs.tsx'; -import ExtendedExample from '@docs/components/ExtendedExample.tsx'; - -A component to use as a header at the top of the screen. -It can contain the screen title, controls such as navigation buttons, menu button etc. - - - - - - - -## Usage -```js -import * as React from 'react'; -import { Appbar } from 'react-native-paper'; - -const MyComponent = () => { - const _goBack = () => console.log('Went back'); - - const _handleSearch = () => console.log('Searching'); - - const _handleMore = () => console.log('Shown more'); - - return ( - - - - - - - ); -}; - -export default MyComponent; -``` - - - ## Props - - - - -
- -### dark - -
- - - -
- -### statusBarHeight - -
- - - -
- -### children (required) - -
- - - -
- -### mode Available in v5.x with theme version 3 - -
- - - -
- -### elevated Available in v5.x with theme version 3 - -
- - - -
- -### theme - -
- - - -
- -### style - -
- - - -
- -### testID - -
- - - - - - - - - ## Theme colors - - - - - diff --git a/docs/6.x/docs/components/Appbar/_meta.json b/docs/6.x/docs/components/Appbar/_meta.json index d4243fea02..8350bf635e 100644 --- a/docs/6.x/docs/components/Appbar/_meta.json +++ b/docs/6.x/docs/components/Appbar/_meta.json @@ -1,7 +1,3 @@ [ - "Appbar", - "AppbarAction", - "AppbarBackAction", - "AppbarContent", - "AppbarHeader" + "Appbar" ] diff --git a/docs/6.x/docs/guides/react-navigation.md b/docs/6.x/docs/guides/react-navigation.md index 6c01200f11..2e655b2e87 100644 --- a/docs/6.x/docs/guides/react-navigation.md +++ b/docs/6.x/docs/guides/react-navigation.md @@ -136,11 +136,7 @@ Now we will implement `CustomNavigationBar` using `AppBar` component: import { Appbar } from 'react-native-paper'; export default function CustomNavigationBar() { - return ( - - - - ); + return ; } ``` @@ -154,11 +150,7 @@ import { getHeaderTitle } from '@react-navigation/elements'; export default function CustomNavigationBar({ route, options }) { const title = getHeaderTitle(options, route.name); - return ( - - - - ); + return ; } ``` @@ -179,10 +171,13 @@ export default function CustomNavigationBar({ const title = getHeaderTitle(options, route.name); return ( - - {back ? : null} - - + ); } ``` @@ -194,8 +189,8 @@ export default function CustomNavigationBar({ Another interesting pattern that can be implemented with `react-native-paper` and `react-navigation` is a "menu" button. Thanks to the `Menu` component we can add a nice looking pop-up to our `Appbar`. To implement this feature we need to make a couple of changes in `CustomNavigationBar`: - Render a `Menu` component -- Pass `Appbar.Action` to the anchor prop -- Add a state to control `Menu` visibility +- Add a trailing action to `Appbar` +- Store the action coordinates and menu visibility in state :::note To have properly working `Menu` component, remember to wrap your root component with the `PaperProvider`: @@ -236,21 +231,41 @@ export default function CustomNavigationBar({ back, }) { const [visible, setVisible] = React.useState(false); + const [menuAnchor, setMenuAnchor] = React.useState({ x: 0, y: 0 }); const openMenu = () => setVisible(true); const closeMenu = () => setVisible(false); const title = getHeaderTitle(options, route.name); return ( - - {back ? : null} - + <> + { + setMenuAnchor({ + x: event.nativeEvent.pageX, + y: event.nativeEvent.pageY, + }); + openMenu(); + }, + }, + ] + } + /> {!back ? ( - } - > + { console.log('Option 1 was pressed'); @@ -272,7 +287,7 @@ export default function CustomNavigationBar({ /> ) : null} - + ); } ``` diff --git a/docs/6.x/docs/guides/theming-with-react-navigation.md b/docs/6.x/docs/guides/theming-with-react-navigation.md index 06be61e5c8..8d28eb8440 100644 --- a/docs/6.x/docs/guides/theming-with-react-navigation.md +++ b/docs/6.x/docs/guides/theming-with-react-navigation.md @@ -249,24 +249,25 @@ Now that the Context is available at every component, all we need to do is impor ```js import React from 'react'; -import { useTheme, Appbar, TouchableRipple, Switch } from 'react-native-paper'; +import { Appbar } from 'react-native-paper'; import { PreferencesContext } from './PreferencesContext'; const Header = ({ scene }) => { - const theme = useTheme(); const { toggleTheme, isThemeDark } = React.useContext(PreferencesContext); return ( - - - - + ]} + /> ); }; ``` diff --git a/docs/6.x/docs/guides/theming.mdx b/docs/6.x/docs/guides/theming.mdx index 261fe128be..b7bfebacb3 100644 --- a/docs/6.x/docs/guides/theming.mdx +++ b/docs/6.x/docs/guides/theming.mdx @@ -503,14 +503,14 @@ Now you can use your `FancyButton` component everywhere instead of using `Button ## Dark Theme Since 3.0 we adapt dark theme to follow [Material design guidelines](https://material.io/design/color/dark-theme.html).
-In contrast to light theme, dark theme by default uses `surface` colour instead of `primary` on large components like `AppBar` or `BottomNavigation`.
+In contrast to light theme, dark theme by default uses `surface` colour instead of `primary` on large components like `BottomNavigation`.
The dark theme adds a white overlay with opacity depending on elevation of surfaces. It uses it for the better accentuation of surface elevation. Using only shadow is highly imperceptible on dark surfaces. We are aware that users often use dark theme in their own ways and may not want to use the default dark theme features from the guidelines.
That's why if you are using dark theme you can switch between two dark theme `mode`s: -- `exact` where everything is like it was before. `Appbar` and `BottomNavigation` will still use primary colour by default.
-- `adaptive` where we follow [Material design guidelines](https://material.io/design/color/dark-theme.html), the surface will use white overlay with opacity to show elevation, `Appbar` and `BottomNavigation` will use surface colour as a background. +- `exact` where everything is like it was before. `BottomNavigation` will still use primary colour by default.
+- `adaptive` where we follow [Material design guidelines](https://material.io/design/color/dark-theme.html), the surface will use white overlay with opacity to show elevation, and `BottomNavigation` will use surface colour as a background. If you don't use a custom theme, Paper will automatically change between the default theme and the default dark theme, depending on device settings. diff --git a/docs/component-docs.config.ts b/docs/component-docs.config.ts index bad25d4eec..bb57ff6940 100644 --- a/docs/component-docs.config.ts +++ b/docs/component-docs.config.ts @@ -26,10 +26,6 @@ const pages = { ActivityIndicator: 'ActivityIndicator', Appbar: { Appbar: 'Appbar/Appbar', - AppbarAction: 'Appbar/AppbarAction', - AppbarBackAction: 'Appbar/AppbarBackAction', - AppbarContent: 'Appbar/AppbarContent', - AppbarHeader: 'Appbar/AppbarHeader', }, Avatar: { AvatarIcon: 'Avatar/AvatarIcon', diff --git a/docs/src/data/componentDocs6x.json b/docs/src/data/componentDocs6x.json index 300c315b99..386d34d750 100644 --- a/docs/src/data/componentDocs6x.json +++ b/docs/src/data/componentDocs6x.json @@ -95,624 +95,41 @@ "Appbar/Appbar": { "filepath": "Appbar/Appbar.tsx", "title": "Appbar", - "description": "A component to display action items in a bar. It can be placed at the top or bottom.\nThe top bar usually contains the screen title, controls such as navigation buttons, menu button etc.\nThe bottom bar usually provides access to a drawer and up to four actions.\n\nBy default Appbar uses primary color as a background, in dark theme with `adaptive` mode it will use surface colour instead.\nSee [Dark Theme](https://callstack.github.io/react-native-paper/docs/guides/theming#dark-theme) for more informations\n\n## Usage\n### Top bar\n```js\nimport * as React from 'react';\nimport { Appbar } from 'react-native-paper';\n\nconst MyComponent = () => (\n \n {}} />\n \n {}} />\n {}} />\n \n);\n\nexport default MyComponent;\n```\n\n### Bottom bar\n```js\nimport * as React from 'react';\nimport { StyleSheet } from 'react-native';\nimport { Appbar, FAB, useTheme } from 'react-native-paper';\nimport { useSafeAreaInsets } from 'react-native-safe-area-context';\n\nconst BOTTOM_APPBAR_HEIGHT = 80;\nconst MEDIUM_FAB_HEIGHT = 56;\n\nconst MyComponent = () => {\n const { bottom } = useSafeAreaInsets();\n const theme = useTheme();\n\n return (\n \n {}} />\n {}} />\n {}} />\n {}} />\n {}}\n style={[\n styles.fab,\n { top: (BOTTOM_APPBAR_HEIGHT - MEDIUM_FAB_HEIGHT) / 2 },\n ]}\n />\n \n );\n};\n\nconst styles = StyleSheet.create({\n bottom: {\n backgroundColor: 'aquamarine',\n position: 'absolute',\n left: 0,\n right: 0,\n bottom: 0,\n },\n fab: {\n position: 'absolute',\n right: 16,\n },\n});\n\nexport default MyComponent;\n```", + "description": "A Material Design app bar for displaying a page headline, navigation, and\ncontextual actions. Appbar supports small, medium flexible, large flexible,\nand search variants. Its surface color automatically changes when content\nhas scrolled, and it accounts for safe-area insets.\n\n## Variants\n\n| `variant` | Purpose |\n| --- | --- |\n| `small` | A compact 64dp app bar with a one-line headline. |\n| `medium-flexible` | A flexible app bar with a two-line headline and optional subtitle or image. |\n| `large-flexible` | A prominent flexible app bar with a two-line headline and optional subtitle or image. |\n| `search` | An app bar containing a centered Paper `Searchbar`. |\n\n## Main props\n\n| Prop | Description |\n| --- | --- |\n| `headline` | Required accessible headline for every non-search variant. |\n| `subtitle` | Optional supporting text for written headlines. |\n| `headlineAlignment` | Aligns headline content to `leading` (default) or `center`. |\n| `headlineImage` | Replaces the visible small headline, or appears above a flexible headline. Images should fit within 32dp height. |\n| `onHeadlinePress` | Makes the headline area interactive; use `headlinePressableProps` for its accessibility state. |\n| `leadingButton` | A back button (`{ type: 'back' }`) or standard icon-button configuration. |\n| `trailingActions` | Standard icon-button configurations, or exactly one `filled`/`tonal` action with optional `wide` width. Every action requires a stable `key` and `aria-label`. |\n| `searchBar` | Required for the `search` variant. Accepts Paper `Searchbar` props except `mode`, `elevation`, `showDivider`, and `theme`. |\n| `isScrolled` | Uses `surfaceContainer` instead of `surface` when content has scrolled. |\n| `safeAreaInsets` | Overrides detected top, left, or right safe-area insets. |\n| `statusBarHeight` | Overrides only the automatic top inset. |\n| `contentStyle` | Styles the headline and subtitle area. |\n| `style` | Styles the app bar and can override its background color. |\n\n## Migrating from the compound API\n\n`Appbar.Header`, `Appbar.Content`, `Appbar.Action`, and\n`Appbar.BackAction` have been removed. Render one `Appbar` and provide its\nheadline, leading button, and trailing actions as props. The former\n`mode=\"medium\"` and `mode=\"large\"` values are now\n`variant=\"medium-flexible\"` and `variant=\"large-flexible\"`; centered\ncontent uses `headlineAlignment=\"center\"`.\n\n## Usage\n\n### Small app bar\n```js\nimport * as React from 'react';\nimport { Appbar } from 'react-native-paper';\n\nconst MyComponent = () => (\n {} }}\n trailingActions={[\n {\n key: 'search',\n icon: 'magnify',\n 'aria-label': 'Search',\n onPress: () => {},\n },\n {\n key: 'more',\n icon: 'dots-vertical',\n 'aria-label': 'More options',\n onPress: () => {},\n },\n ]}\n />\n);\n\nexport default MyComponent;\n```\n\n### Flexible app bar\n```js\n\n```\n\n### Search app bar\n```js\n {} }}\n searchBar={{\n placeholder: 'Search messages',\n value: query,\n onChangeText: setQuery,\n }}\n/>\n```", "link": "appbar", "data": { - "description": "A component to display action items in a bar. It can be placed at the top or bottom.\nThe top bar usually contains the screen title, controls such as navigation buttons, menu button etc.\nThe bottom bar usually provides access to a drawer and up to four actions.\n\nBy default Appbar uses primary color as a background, in dark theme with `adaptive` mode it will use surface colour instead.\nSee [Dark Theme](https://callstack.github.io/react-native-paper/docs/guides/theming#dark-theme) for more informations\n\n## Usage\n### Top bar\n```js\nimport * as React from 'react';\nimport { Appbar } from 'react-native-paper';\n\nconst MyComponent = () => (\n \n {}} />\n \n {}} />\n {}} />\n \n);\n\nexport default MyComponent;\n```\n\n### Bottom bar\n```js\nimport * as React from 'react';\nimport { StyleSheet } from 'react-native';\nimport { Appbar, FAB, useTheme } from 'react-native-paper';\nimport { useSafeAreaInsets } from 'react-native-safe-area-context';\n\nconst BOTTOM_APPBAR_HEIGHT = 80;\nconst MEDIUM_FAB_HEIGHT = 56;\n\nconst MyComponent = () => {\n const { bottom } = useSafeAreaInsets();\n const theme = useTheme();\n\n return (\n \n {}} />\n {}} />\n {}} />\n {}} />\n {}}\n style={[\n styles.fab,\n { top: (BOTTOM_APPBAR_HEIGHT - MEDIUM_FAB_HEIGHT) / 2 },\n ]}\n />\n \n );\n};\n\nconst styles = StyleSheet.create({\n bottom: {\n backgroundColor: 'aquamarine',\n position: 'absolute',\n left: 0,\n right: 0,\n bottom: 0,\n },\n fab: {\n position: 'absolute',\n right: 16,\n },\n});\n\nexport default MyComponent;\n```", + "description": "A Material Design app bar for displaying a page headline, navigation, and\ncontextual actions. Appbar supports small, medium flexible, large flexible,\nand search variants. Its surface color automatically changes when content\nhas scrolled, and it accounts for safe-area insets.\n\n## Variants\n\n| `variant` | Purpose |\n| --- | --- |\n| `small` | A compact 64dp app bar with a one-line headline. |\n| `medium-flexible` | A flexible app bar with a two-line headline and optional subtitle or image. |\n| `large-flexible` | A prominent flexible app bar with a two-line headline and optional subtitle or image. |\n| `search` | An app bar containing a centered Paper `Searchbar`. |\n\n## Main props\n\n| Prop | Description |\n| --- | --- |\n| `headline` | Required accessible headline for every non-search variant. |\n| `subtitle` | Optional supporting text for written headlines. |\n| `headlineAlignment` | Aligns headline content to `leading` (default) or `center`. |\n| `headlineImage` | Replaces the visible small headline, or appears above a flexible headline. Images should fit within 32dp height. |\n| `onHeadlinePress` | Makes the headline area interactive; use `headlinePressableProps` for its accessibility state. |\n| `leadingButton` | A back button (`{ type: 'back' }`) or standard icon-button configuration. |\n| `trailingActions` | Standard icon-button configurations, or exactly one `filled`/`tonal` action with optional `wide` width. Every action requires a stable `key` and `aria-label`. |\n| `searchBar` | Required for the `search` variant. Accepts Paper `Searchbar` props except `mode`, `elevation`, `showDivider`, and `theme`. |\n| `isScrolled` | Uses `surfaceContainer` instead of `surface` when content has scrolled. |\n| `safeAreaInsets` | Overrides detected top, left, or right safe-area insets. |\n| `statusBarHeight` | Overrides only the automatic top inset. |\n| `contentStyle` | Styles the headline and subtitle area. |\n| `style` | Styles the app bar and can override its background color. |\n\n## Migrating from the compound API\n\n`Appbar.Header`, `Appbar.Content`, `Appbar.Action`, and\n`Appbar.BackAction` have been removed. Render one `Appbar` and provide its\nheadline, leading button, and trailing actions as props. The former\n`mode=\"medium\"` and `mode=\"large\"` values are now\n`variant=\"medium-flexible\"` and `variant=\"large-flexible\"`; centered\ncontent uses `headlineAlignment=\"center\"`.\n\n## Usage\n\n### Small app bar\n```js\nimport * as React from 'react';\nimport { Appbar } from 'react-native-paper';\n\nconst MyComponent = () => (\n {} }}\n trailingActions={[\n {\n key: 'search',\n icon: 'magnify',\n 'aria-label': 'Search',\n onPress: () => {},\n },\n {\n key: 'more',\n icon: 'dots-vertical',\n 'aria-label': 'More options',\n onPress: () => {},\n },\n ]}\n />\n);\n\nexport default MyComponent;\n```\n\n### Flexible app bar\n```js\n\n```\n\n### Search app bar\n```js\n {} }}\n searchBar={{\n placeholder: 'Search messages',\n value: query,\n onChangeText: setQuery,\n }}\n/>\n```", "displayName": "Appbar", "methods": [], "statics": [], "props": { - "dark": { - "required": false, - "tsType": { - "name": "boolean" - }, - "description": "Whether the background color is a dark color. A dark appbar will render light text and vice-versa." - }, - "children": { - "required": true, - "tsType": { - "name": "ReactReactNode", - "raw": "React.ReactNode" - }, - "description": "Content of the `Appbar`." - }, - "mode": { - "required": false, - "tsType": { - "name": "union", - "raw": "'small' | 'medium' | 'large' | 'center-aligned'", - "elements": [ - { - "name": "literal", - "value": "'small'" - }, - { - "name": "literal", - "value": "'medium'" - }, - { - "name": "literal", - "value": "'large'" - }, - { - "name": "literal", - "value": "'center-aligned'" - } - ] - }, - "description": "@supported Available in v5.x with theme version 3\n\nMode of the Appbar.\n- `small` - Appbar with default height (64).\n- `medium` - Appbar with medium height (112).\n- `large` - Appbar with large height (152).\n- `center-aligned` - Appbar with default height and center-aligned title.", - "defaultValue": { - "value": "'small'", - "computed": false - } - }, - "elevated": { - "required": false, - "tsType": { - "name": "boolean" - }, - "description": "@supported Available in v5.x with theme version 3\nWhether Appbar background should have the elevation along with primary color pigment." - }, - "safeAreaInsets": { - "required": false, - "tsType": { - "name": "signature", - "type": "object", - "raw": "{\n bottom?: number;\n top?: number;\n left?: number;\n right?: number;\n}", - "signature": { - "properties": [ - { - "key": "bottom", - "value": { - "name": "number", - "required": false - } - }, - { - "key": "top", - "value": { - "name": "number", - "required": false - } - }, - { - "key": "left", - "value": { - "name": "number", - "required": false - } - }, - { - "key": "right", - "value": { - "name": "number", - "required": false - } - } - ] - } - }, - "description": "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." - }, - "theme": { - "required": false, - "tsType": { - "name": "ThemeProp" - }, - "description": "" - }, - "style": { - "required": false, - "tsType": { - "name": "Animated.WithAnimatedValue", - "elements": [ - { - "name": "StyleProp", - "elements": [ - { - "name": "ViewStyle" - } - ], - "raw": "StyleProp" - } - ], - "raw": "Animated.WithAnimatedValue>" - }, - "description": "" - } - } - }, - "type": "component", - "dependencies": [ - "src/components/Appbar/Appbar.tsx" - ] - }, - "Appbar/AppbarAction": { - "filepath": "Appbar/AppbarAction.tsx", - "title": "Appbar.Action", - "description": "A component used to display an action item in the appbar.\n\n## Usage\n```js\nimport * as React from 'react';\nimport { Appbar } from 'react-native-paper';\nimport { Platform } from 'react-native';\n\nconst MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical';\n\nconst MyComponent = () => (\n \n \n {}} />\n {}} />\n \n);\n\nexport default MyComponent;\n```", - "link": "appbar-action", - "data": { - "description": "A component used to display an action item in the appbar.\n\n## Usage\n```js\nimport * as React from 'react';\nimport { Appbar } from 'react-native-paper';\nimport { Platform } from 'react-native';\n\nconst MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical';\n\nconst MyComponent = () => (\n \n \n {}} />\n {}} />\n \n);\n\nexport default MyComponent;\n```", - "displayName": "Appbar.Action", - "methods": [], - "statics": [], - "props": { - "color": { - "required": false, - "tsType": { - "name": "ColorValue" - }, - "description": "Custom color for action icon." - }, - "icon": { - "required": true, - "tsType": { - "name": "IconSource" - }, - "description": "Name of the icon to show." - }, - "size": { - "required": false, - "tsType": { - "name": "number" - }, - "description": "Optional icon size.", - "defaultValue": { - "value": "24", - "computed": false - } - }, - "disabled": { - "required": false, - "tsType": { - "name": "boolean" - }, - "description": "Whether the button is disabled. A disabled button is greyed out and `onPress` is not called on touch." - }, - "aria-label": { - "required": false, - "tsType": { - "name": "string" - }, - "description": "Accessibility label for the button. This is read by the screen reader when the user taps the button." - }, - "onPress": { - "required": false, - "tsType": { - "name": "signature", - "type": "function", - "raw": "() => void", - "signature": { - "arguments": [], - "return": { - "name": "void" - } - } - }, - "description": "Function to execute on press." - }, - "isLeading": { - "required": false, - "tsType": { - "name": "boolean" - }, - "description": "@supported Available in v5.x with theme version 3\n\nWhether it's the leading button. Note: If `Appbar.BackAction` is present, it will be rendered before any `isLeading` icons." - }, - "style": { - "required": false, - "tsType": { - "name": "Animated.WithAnimatedValue", - "elements": [ - { - "name": "StyleProp", - "elements": [ - { - "name": "ViewStyle" - } - ], - "raw": "StyleProp" - } - ], - "raw": "Animated.WithAnimatedValue>" - }, - "description": "" - }, - "ref": { - "required": false, - "tsType": { - "name": "ReactRef", - "raw": "React.Ref", - "elements": [ - { - "name": "View" - } - ] - }, - "description": "" - }, - "theme": { - "required": false, - "tsType": { - "name": "ThemeProp" - }, - "description": "" - } - } - }, - "type": "component", - "dependencies": [ - "src/components/Appbar/AppbarAction.tsx" - ], - "group": "Appbar" - }, - "Appbar/AppbarBackAction": { - "filepath": "Appbar/AppbarBackAction.tsx", - "title": "Appbar.BackAction", - "description": "A component used to display a back button in the appbar.\n\n## Usage\n```js\nimport * as React from 'react';\nimport { Appbar } from 'react-native-paper';\n\nconst MyComponent = () => (\n \n {}} />\n \n);\n\nexport default MyComponent;\n```", - "link": "appbar-back-action", - "data": { - "description": "A component used to display a back button in the appbar.\n\n## Usage\n```js\nimport * as React from 'react';\nimport { Appbar } from 'react-native-paper';\n\nconst MyComponent = () => (\n \n {}} />\n \n);\n\nexport default MyComponent;\n```", - "displayName": "Appbar.BackAction", - "methods": [], - "statics": [], - "props": { - "color": { - "required": false, - "tsType": { - "name": "ColorValue" - }, - "description": "Custom color for back icon." - }, - "size": { - "required": false, - "tsType": { - "name": "number" - }, - "description": "Optional icon size." - }, - "disabled": { - "required": false, - "tsType": { - "name": "boolean" - }, - "description": "Whether the button is disabled. A disabled button is greyed out and `onPress` is not called on touch." - }, - "aria-label": { - "required": false, - "tsType": { - "name": "string" - }, - "description": "Accessibility label for the button. This is read by the screen reader when the user taps the button.", - "defaultValue": { - "value": "'Back'", - "computed": false - } - }, - "onPress": { - "required": false, - "tsType": { - "name": "signature", - "type": "function", - "raw": "(e: GestureResponderEvent) => void", - "signature": { - "arguments": [ - { - "name": "e", - "type": { - "name": "GestureResponderEvent" - } - } - ], - "return": { - "name": "void" - } - } - }, - "description": "Function to execute on press." - }, - "style": { - "required": false, - "tsType": { - "name": "Animated.WithAnimatedValue", - "elements": [ - { - "name": "StyleProp", - "elements": [ - { - "name": "ViewStyle" - } - ], - "raw": "StyleProp" - } - ], - "raw": "Animated.WithAnimatedValue>" - }, - "description": "" - }, - "ref": { - "required": false, - "tsType": { - "name": "ReactRef", - "raw": "React.Ref", - "elements": [ - { - "name": "View" - } - ] - }, - "description": "" - } - } - }, - "type": "component", - "dependencies": [ - "src/components/Appbar/AppbarBackAction.tsx" - ], - "group": "Appbar" - }, - "Appbar/AppbarContent": { - "filepath": "Appbar/AppbarContent.tsx", - "title": "Appbar.Content", - "description": "A component used to display a title in an appbar.\n\n## Usage\n```js\nimport * as React from 'react';\nimport { Appbar } from 'react-native-paper';\n\nconst MyComponent = () => (\n \n \n \n);\n\nexport default MyComponent;\n```", - "link": "appbar-content", - "data": { - "description": "A component used to display a title in an appbar.\n\n## Usage\n```js\nimport * as React from 'react';\nimport { Appbar } from 'react-native-paper';\n\nconst MyComponent = () => (\n \n \n \n);\n\nexport default MyComponent;\n```", - "displayName": "Appbar.Content", - "methods": [], - "statics": [], - "props": { - "title": { - "required": true, - "tsType": { - "name": "ReactReactNode", - "raw": "React.ReactNode" - }, - "description": "Text or component for the title." - }, - "titleStyle": { - "required": false, - "tsType": { - "name": "StyleProp", - "elements": [ - { - "name": "TextStyle" - } - ], - "raw": "StyleProp" - }, - "description": "Style for the title, if `title` is a string." - }, - "titleRef": { - "required": false, - "tsType": { - "name": "ReactRefObject", - "raw": "React.RefObject", - "elements": [ - { - "name": "TextRef" - } - ] - }, - "description": "Reference for the title." - }, - "onPress": { - "required": false, - "tsType": { - "name": "signature", - "type": "function", - "raw": "(e: GestureResponderEvent) => void", - "signature": { - "arguments": [ - { - "name": "e", - "type": { - "name": "GestureResponderEvent" - } - } - ], - "return": { - "name": "void" - } - } - }, - "description": "Function to execute on press." - }, - "disabled": { - "required": false, - "tsType": { - "name": "boolean" - }, - "description": "If true, disable all interactions for this component." - }, - "color": { - "required": false, - "tsType": { - "name": "string" - }, - "description": "Custom color for the text." - }, - "titleMaxFontSizeMultiplier": { - "required": false, - "tsType": { - "name": "number" - }, - "description": "Specifies the largest possible scale a title font can reach." - }, - "mode": { - "required": false, - "tsType": { - "name": "union", - "raw": "'small' | 'medium' | 'large' | 'center-aligned'", - "elements": [ - { - "name": "literal", - "value": "'small'" - }, - { - "name": "literal", - "value": "'medium'" - }, - { - "name": "literal", - "value": "'large'" - }, - { - "name": "literal", - "value": "'center-aligned'" - } - ] - }, - "description": "@internal", + "headlineAlignment": { "defaultValue": { - "value": "'small'", + "value": "'leading'", "computed": false - } - }, - "style": { - "required": false, - "tsType": { - "name": "StyleProp", - "elements": [ - { - "name": "ViewStyle" - } - ], - "raw": "StyleProp" }, - "description": "" - }, - "theme": { "required": false, - "tsType": { - "name": "ThemeProp" - }, "description": "" }, - "testID": { - "required": false, - "tsType": { - "name": "string" - }, - "description": "testID to be used on tests.", + "isScrolled": { "defaultValue": { - "value": "'appbar-content'", + "value": "false", "computed": false - } - } - } - }, - "type": "component", - "dependencies": [ - "src/components/Appbar/AppbarContent.tsx" - ], - "group": "Appbar" - }, - "Appbar/AppbarHeader": { - "filepath": "Appbar/AppbarHeader.tsx", - "title": "Appbar.Header", - "description": "A component to use as a header at the top of the screen.\nIt can contain the screen title, controls such as navigation buttons, menu button etc.\n\n## Usage\n```js\nimport * as React from 'react';\nimport { Appbar } from 'react-native-paper';\n\nconst MyComponent = () => {\n const _goBack = () => console.log('Went back');\n\n const _handleSearch = () => console.log('Searching');\n\n const _handleMore = () => console.log('Shown more');\n\n return (\n \n \n \n \n \n \n );\n};\n\nexport default MyComponent;\n```", - "link": "appbar-header", - "data": { - "description": "A component to use as a header at the top of the screen.\nIt can contain the screen title, controls such as navigation buttons, menu button etc.\n\n## Usage\n```js\nimport * as React from 'react';\nimport { Appbar } from 'react-native-paper';\n\nconst MyComponent = () => {\n const _goBack = () => console.log('Went back');\n\n const _handleSearch = () => console.log('Searching');\n\n const _handleMore = () => console.log('Shown more');\n\n return (\n \n \n \n \n \n \n );\n};\n\nexport default MyComponent;\n```", - "displayName": "Appbar.Header", - "methods": [], - "statics": [], - "props": { - "dark": { - "required": false, - "tsType": { - "name": "boolean" - }, - "description": "Whether the background color is a dark color. A dark header will render light text and vice-versa." - }, - "statusBarHeight": { - "required": false, - "tsType": { - "name": "number" - }, - "description": "Extra padding to add at the top of header to account for translucent status bar.\nThis is automatically handled on iOS >= 11 including iPhone X using `SafeAreaView`.\nIf you are using Expo, we assume translucent status bar and set a height for status bar automatically.\nPass `0` or a custom value to disable the default behaviour, and customize the height." - }, - "children": { - "required": true, - "tsType": { - "name": "ReactReactNode", - "raw": "React.ReactNode" }, - "description": "Content of the header." - }, - "mode": { "required": false, - "tsType": { - "name": "union", - "raw": "'small' | 'medium' | 'large' | 'center-aligned'", - "elements": [ - { - "name": "literal", - "value": "'small'" - }, - { - "name": "literal", - "value": "'medium'" - }, - { - "name": "literal", - "value": "'large'" - }, - { - "name": "literal", - "value": "'center-aligned'" - } - ] - }, - "description": "@supported Available in v5.x with theme version 3\n\nMode of the Appbar.\n- `small` - Appbar with default height (64).\n- `medium` - Appbar with medium height (112).\n- `large` - Appbar with large height (152).\n- `center-aligned` - Appbar with default height and center-aligned title.", - "defaultValue": { - "value": "Platform.OS === 'ios' ? 'center-aligned' : 'small'", - "computed": false - } + "description": "" }, - "elevated": { - "required": false, - "tsType": { - "name": "boolean" - }, - "description": "@supported Available in v5.x with theme version 3\nWhether Appbar background should have the elevation along with primary color pigment.", + "testID": { "defaultValue": { - "value": "false", + "value": "'appbar'", "computed": false - } - }, - "theme": { - "required": false, - "tsType": { - "name": "ThemeProp" }, - "description": "" - }, - "style": { "required": false, - "tsType": { - "name": "Animated.WithAnimatedValue", - "elements": [ - { - "name": "StyleProp", - "elements": [ - { - "name": "ViewStyle" - } - ], - "raw": "StyleProp" - } - ], - "raw": "Animated.WithAnimatedValue>" - }, "description": "" }, - "testID": { + "trailingActions": { "defaultValue": { - "value": "'appbar-header'", + "value": "[]", "computed": false }, "required": false, @@ -722,9 +139,8 @@ }, "type": "component", "dependencies": [ - "src/components/Appbar/AppbarHeader.tsx" - ], - "group": "Appbar" + "src/components/Appbar/Appbar.tsx" + ] }, "Avatar/AvatarIcon": { "filepath": "Avatar/AvatarIcon.tsx", diff --git a/docs/src/data/screenshots.ts b/docs/src/data/screenshots.ts index 92bf8f2788..a30ca3bff6 100644 --- a/docs/src/data/screenshots.ts +++ b/docs/src/data/screenshots.ts @@ -1,15 +1,5 @@ export const screenshots = { ActivityIndicator: 'screenshots/activity-indicator.gif', - Appbar: 'screenshots/appbar.png', - 'Appbar.Action': 'screenshots/appbar-action-android.png', - 'Appbar.BackAction': 'screenshots/appbar-backaction-android.png', - 'Appbar.Content': 'screenshots/appbar-content.png', - 'Appbar.Header': { - small: 'screenshots/appbar-small.png', - medium: 'screenshots/appbar-medium.png', - large: 'screenshots/appbar-large.png', - 'center-aligned': 'screenshots/appbar-center-aligned.png', - }, 'Avatar.Icon': 'screenshots/avatar-icon.png', 'Avatar.Image': 'screenshots/avatar-image.png', 'Avatar.Text': 'screenshots/avatar-text.png', diff --git a/docs/src/data/themeColors.ts b/docs/src/data/themeColors.ts index 20f16962f7..d347b65889 100644 --- a/docs/src/data/themeColors.ts +++ b/docs/src/data/themeColors.ts @@ -8,29 +8,20 @@ export const themeColors = { default: { backgroundColor: 'theme.colors.surface', }, - elevated: { - backgroundColor: 'theme.colors.elevation.level2', + scrolled: { + backgroundColor: 'theme.colors.surfaceContainer', }, - }, - 'Appbar.Action': { - 'leading icon': { + 'leading action': { iconColor: 'theme.colors.onSurface', }, - 'not leading icon': { + 'trailing action': { iconColor: 'theme.colors.onSurfaceVariant', }, - }, - 'Appbar.Content': { - '-': { + headline: { textColor: 'theme.colors.onSurface', }, - }, - 'Appbar.Header': { - default: { - backgroundColor: 'theme.colors.surface', - }, - elevated: { - backgroundColor: 'theme.colors.elevation.level2', + subtitle: { + textColor: 'theme.colors.onSurfaceVariant', }, }, Banner: { diff --git a/example/src/ExampleList.tsx b/example/src/ExampleList.tsx index bd30b8feb6..8a2646d798 100644 --- a/example/src/ExampleList.tsx +++ b/example/src/ExampleList.tsx @@ -6,7 +6,6 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context'; import ActivityIndicatorExample from './Examples/ActivityIndicatorExample'; import AppbarExample from './Examples/AppbarExample'; -import AppbarV3Example from './Examples/AppbarV3Example'; import AvatarExample from './Examples/AvatarExample'; import BadgeExample from './Examples/BadgeExample'; import BannerExample from './Examples/BannerExample'; @@ -52,7 +51,6 @@ import TouchableRippleExample from './Examples/TouchableRippleExample'; export const mainExamples = { ActivityIndicator: ActivityIndicatorExample, Appbar: AppbarExample, - AppbarV3: AppbarV3Example, Avatar: AvatarExample, Badge: BadgeExample, Banner: BannerExample, diff --git a/example/src/Examples/AppbarExample.tsx b/example/src/Examples/AppbarExample.tsx index 10f4b0bb92..17f20da4ee 100644 --- a/example/src/Examples/AppbarExample.tsx +++ b/example/src/Examples/AppbarExample.tsx @@ -1,122 +1,320 @@ import * as React from 'react'; -import { Platform, StyleSheet, View } from 'react-native'; +import { + Image, + Platform, + StyleSheet, + useWindowDimensions, + View, +} from 'react-native'; +import type { NativeScrollEvent, NativeSyntheticEvent } from 'react-native'; import { useNavigation } from '@react-navigation/native'; import { Appbar, - FAB, List, Palette, RadioButton, Snackbar, Switch, Text, - useTheme, +} from 'react-native-paper'; +import type { + AppbarFilledTrailingAction, + AppbarHeadlineAlignment, + AppbarLeadingButton, + AppbarStandardTrailingAction, + AppbarTrailingActions, + AppbarVariant, } from 'react-native-paper'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import ScreenWrapper from '../ScreenWrapper'; -type AppbarModes = 'small' | 'medium' | 'large' | 'center-aligned'; +type FilledTrailingActionVariant = AppbarFilledTrailingAction['variant']; +type FilledTrailingActionWidth = NonNullable< + AppbarFilledTrailingAction['width'] +>; const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical'; -const MEDIUM_FAB_HEIGHT = 56; + +type SearchAppbarHeaderProps = { + trailingActions: AppbarStandardTrailingAction[]; + isScrolled: boolean; + leadingButton?: AppbarLeadingButton; + showCustomColor: boolean; +}; + +const SearchAppbarHeader = ({ + trailingActions, + isScrolled, + leadingButton, + showCustomColor, +}: SearchAppbarHeaderProps) => { + const [searchQuery, setSearchQuery] = React.useState(''); + + return ( + + ); +}; const AppbarExample = () => { const navigation = useNavigation('Appbar'); - const [showLeftIcon, setShowLeftIcon] = React.useState(true); + const [showLeadingButton, setShowLeadingButton] = React.useState(true); const [showSubtitle, setShowSubtitle] = React.useState(true); + const [showHeadlineImage, setShowHeadlineImage] = React.useState(false); const [showSearchIcon, setShowSearchIcon] = React.useState(true); const [showMoreIcon, setShowMoreIcon] = React.useState(true); const [showCustomColor, setShowCustomColor] = React.useState(false); - const [appbarMode, setAppbarMode] = React.useState('small'); + const [appbarConfiguration, setAppbarConfiguration] = + React.useState('small'); + const [isHeadlineCentered, setIsHeadlineCentered] = React.useState(false); const [showCalendarIcon, setShowCalendarIcon] = React.useState(false); - const [showElevated, setShowElevated] = React.useState(false); + const [showFilledTrailingAction, setShowFilledTrailingAction] = + React.useState(false); + const [filledTrailingActionVariant, setFilledTrailingActionVariant] = + React.useState('filled'); + const [filledTrailingActionWidth, setFilledTrailingActionWidth] = + React.useState('default'); + const [isScrolled, setIsScrolled] = React.useState(false); const [showSnackbar, setShowSnackbar] = React.useState(false); - const theme = useTheme(); - const { bottom, left, right } = useSafeAreaInsets(); - const height = 80; - - const isCenterAlignedMode = appbarMode === 'center-aligned'; + const { bottom } = useSafeAreaInsets(); + const { height: windowHeight } = useWindowDimensions(); + const headlineAlignment: AppbarHeadlineAlignment = isHeadlineCentered + ? 'center' + : 'leading'; React.useLayoutEffect(() => { + const standardTrailingActions: AppbarStandardTrailingAction[] = []; + + if (showCalendarIcon) { + standardTrailingActions.push({ + key: 'calendar', + icon: 'calendar', + 'aria-label': 'Calendar', + onPress: () => {}, + }); + } + + if (showSearchIcon && appbarConfiguration !== 'search') { + standardTrailingActions.push({ + key: 'search', + icon: 'magnify', + 'aria-label': 'Search', + onPress: () => {}, + }); + } + + if (showMoreIcon) { + standardTrailingActions.push({ + key: 'more', + icon: MORE_ICON, + 'aria-label': 'More options', + onPress: () => {}, + }); + } + + const trailingActions: AppbarTrailingActions = showFilledTrailingAction + ? [ + { + key: 'share', + icon: 'share-variant', + 'aria-label': 'Share', + variant: filledTrailingActionVariant, + width: filledTrailingActionWidth, + onPress: () => {}, + }, + ] + : standardTrailingActions; + + const leadingButton = showLeadingButton + ? { + type: 'back' as const, + onPress: () => navigation.goBack(), + } + : undefined; + const headlineImage = ( + + ); + const commonProps = { + headlineAlignment, + isScrolled, + leadingButton, + onHeadlinePress: () => setShowSnackbar(true), + style: showCustomColor ? styles.customColor : null, + trailingActions, + }; + navigation.setOptions({ - header: () => ( - - {showLeftIcon && ( - navigation.goBack()} /> - )} - setShowSnackbar(true)} + header: () => { + if (appbarConfiguration === 'search') { + return ( + + ); + } + + if (appbarConfiguration === 'small') { + return showHeadlineImage ? ( + + ) : ( + + ); + } + + return showHeadlineImage ? ( + + ) : ( + - {isCenterAlignedMode - ? false - : showCalendarIcon && ( - {}} /> - )} - {showSearchIcon && ( - {}} /> - )} - {showMoreIcon && ( - {}} /> - )} - - ), + ); + }, }); }, [ + appbarConfiguration, + filledTrailingActionVariant, + filledTrailingActionWidth, navigation, - showLeftIcon, - showSubtitle, - showSearchIcon, - showMoreIcon, - showCustomColor, - appbarMode, showCalendarIcon, - isCenterAlignedMode, - showElevated, + showCustomColor, + showFilledTrailingAction, + showLeadingButton, + showMoreIcon, + isScrolled, + showSearchIcon, + showSubtitle, + showHeadlineImage, + headlineAlignment, ]); - const renderFAB = () => { - return ( - {}} - style={[styles.fab, { top: (height - MEDIUM_FAB_HEIGHT) / 2 }]} - /> - ); - }; + const handleScroll = React.useCallback( + ({ nativeEvent }: NativeSyntheticEvent) => { + const nextIsScrolled = nativeEvent.contentOffset.y > 1; + + setIsScrolled((currentIsScrolled) => + currentIsScrolled === nextIsScrolled + ? currentIsScrolled + : nextIsScrolled + ); + }, + [] + ); const renderDefaultOptions = () => ( <> - Left icon - + Leading button + Subtitle - + + + + Headline image + + + + Center headline and subtitle + + + + Filled trailing action + Search icon - + More icon - + Calendar icon @@ -124,73 +322,110 @@ const AppbarExample = () => { Custom Color - - Elevated - - ); return ( <> + + + {renderDefaultOptions()} - + {showFilledTrailingAction ? ( + + Style + { + if (value === 'filled' || value === 'tonal') { + setFilledTrailingActionVariant(value); + } + }} + > + + Primary filled + + + + Tonal filled + + + + Width + { + if (value === 'default' || value === 'wide') { + setFilledTrailingActionWidth(value); + } + }} + > + + Default + + + + Wide + + + + + ) : null} + - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - setAppbarMode(value as AppbarModes) - } + value={appbarConfiguration} + onValueChange={(value: string) => { + if ( + value === 'small' || + value === 'search' || + value === 'medium-flexible' || + value === 'large-flexible' + ) { + setAppbarConfiguration(value); + } + }} > - Small (default) - + Search + - Medium - + Small (default) + - Large - + Medium flexible + - Center-aligned - + Large flexible + - - {}} /> - {}} /> - {}} /> - {}} /> - {renderFAB()} - setShowSnackbar(false)} duration={Snackbar.DURATION_SHORT} > - Heading pressed + Headline pressed ); @@ -211,17 +446,11 @@ const styles = StyleSheet.create({ paddingVertical: 8, paddingHorizontal: 16, }, - bottom: { - position: 'absolute', - left: 0, - right: 0, - bottom: 0, - }, - fab: { - position: 'absolute', - right: 16, - }, customColor: { backgroundColor: Palette.secondary80, }, + headlineImage: { + width: 32, + height: 32, + }, }); diff --git a/example/src/Examples/AppbarV3Example.tsx b/example/src/Examples/AppbarV3Example.tsx deleted file mode 100644 index e737fcae64..0000000000 --- a/example/src/Examples/AppbarV3Example.tsx +++ /dev/null @@ -1,456 +0,0 @@ -import * as React from 'react'; -import { - Image, - Platform, - StyleSheet, - useWindowDimensions, - View, -} from 'react-native'; -import type { NativeScrollEvent, NativeSyntheticEvent } from 'react-native'; - -import { useNavigation } from '@react-navigation/native'; -import { - AppbarV3, - List, - Palette, - RadioButton, - Snackbar, - Switch, - Text, -} from 'react-native-paper'; -import type { - AppbarV3FilledTrailingAction, - AppbarV3HeadlineAlignment, - AppbarV3LeadingButton, - AppbarV3StandardTrailingAction, - AppbarV3TrailingActions, - AppbarV3Variant, -} from 'react-native-paper'; -import { useSafeAreaInsets } from 'react-native-safe-area-context'; - -import ScreenWrapper from '../ScreenWrapper'; - -type FilledTrailingActionVariant = AppbarV3FilledTrailingAction['variant']; -type FilledTrailingActionWidth = NonNullable< - AppbarV3FilledTrailingAction['width'] ->; - -const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical'; - -type SearchAppbarHeaderProps = { - trailingActions: AppbarV3StandardTrailingAction[]; - isScrolled: boolean; - leadingButton?: AppbarV3LeadingButton; - showCustomColor: boolean; -}; - -const SearchAppbarHeader = ({ - trailingActions, - isScrolled, - leadingButton, - showCustomColor, -}: SearchAppbarHeaderProps) => { - const [searchQuery, setSearchQuery] = React.useState(''); - - return ( - - ); -}; - -const AppbarV3Example = () => { - const navigation = useNavigation('AppbarV3'); - - const [showLeadingButton, setShowLeadingButton] = React.useState(true); - const [showSubtitle, setShowSubtitle] = React.useState(true); - const [showHeadlineImage, setShowHeadlineImage] = React.useState(false); - const [showSearchIcon, setShowSearchIcon] = React.useState(true); - const [showMoreIcon, setShowMoreIcon] = React.useState(true); - const [showCustomColor, setShowCustomColor] = React.useState(false); - const [appbarConfiguration, setAppbarConfiguration] = - React.useState('small'); - const [isHeadlineCentered, setIsHeadlineCentered] = React.useState(false); - const [showCalendarIcon, setShowCalendarIcon] = React.useState(false); - const [showFilledTrailingAction, setShowFilledTrailingAction] = - React.useState(false); - const [filledTrailingActionVariant, setFilledTrailingActionVariant] = - React.useState('filled'); - const [filledTrailingActionWidth, setFilledTrailingActionWidth] = - React.useState('default'); - const [isScrolled, setIsScrolled] = React.useState(false); - const [showSnackbar, setShowSnackbar] = React.useState(false); - - const { bottom } = useSafeAreaInsets(); - const { height: windowHeight } = useWindowDimensions(); - const headlineAlignment: AppbarV3HeadlineAlignment = isHeadlineCentered - ? 'center' - : 'leading'; - - React.useLayoutEffect(() => { - const standardTrailingActions: AppbarV3StandardTrailingAction[] = []; - - if (showCalendarIcon) { - standardTrailingActions.push({ - key: 'calendar', - icon: 'calendar', - 'aria-label': 'Calendar', - onPress: () => {}, - }); - } - - if (showSearchIcon && appbarConfiguration !== 'search') { - standardTrailingActions.push({ - key: 'search', - icon: 'magnify', - 'aria-label': 'Search', - onPress: () => {}, - }); - } - - if (showMoreIcon) { - standardTrailingActions.push({ - key: 'more', - icon: MORE_ICON, - 'aria-label': 'More options', - onPress: () => {}, - }); - } - - const trailingActions: AppbarV3TrailingActions = showFilledTrailingAction - ? [ - { - key: 'share', - icon: 'share-variant', - 'aria-label': 'Share', - variant: filledTrailingActionVariant, - width: filledTrailingActionWidth, - onPress: () => {}, - }, - ] - : standardTrailingActions; - - const leadingButton = showLeadingButton - ? { - type: 'back' as const, - onPress: () => navigation.goBack(), - } - : undefined; - const headlineImage = ( - - ); - const commonProps = { - headlineAlignment, - isScrolled, - leadingButton, - onHeadlinePress: () => setShowSnackbar(true), - style: showCustomColor ? styles.customColor : null, - trailingActions, - }; - - navigation.setOptions({ - header: () => { - if (appbarConfiguration === 'search') { - return ( - - ); - } - - if (appbarConfiguration === 'small') { - return showHeadlineImage ? ( - - ) : ( - - ); - } - - return showHeadlineImage ? ( - - ) : ( - - ); - }, - }); - }, [ - appbarConfiguration, - filledTrailingActionVariant, - filledTrailingActionWidth, - navigation, - showCalendarIcon, - showCustomColor, - showFilledTrailingAction, - showLeadingButton, - showMoreIcon, - isScrolled, - showSearchIcon, - showSubtitle, - showHeadlineImage, - headlineAlignment, - ]); - - const handleScroll = React.useCallback( - ({ nativeEvent }: NativeSyntheticEvent) => { - const nextIsScrolled = nativeEvent.contentOffset.y > 1; - - setIsScrolled((currentIsScrolled) => - currentIsScrolled === nextIsScrolled - ? currentIsScrolled - : nextIsScrolled - ); - }, - [] - ); - - const renderDefaultOptions = () => ( - <> - - Leading button - - - - Subtitle - - - - Headline image - - - - Center headline and subtitle - - - - Filled trailing action - - - - Search icon - - - - More icon - - - - Calendar icon - - - - Custom Color - - - - ); - - return ( - <> - - - - - - {renderDefaultOptions()} - - {showFilledTrailingAction ? ( - - Style - { - if (value === 'filled' || value === 'tonal') { - setFilledTrailingActionVariant(value); - } - }} - > - - Primary filled - - - - Tonal filled - - - - Width - { - if (value === 'default' || value === 'wide') { - setFilledTrailingActionWidth(value); - } - }} - > - - Default - - - - Wide - - - - - ) : null} - - { - if ( - value === 'small' || - value === 'search' || - value === 'medium-flexible' || - value === 'large-flexible' - ) { - setAppbarConfiguration(value); - } - }} - > - - Search - - - - Small (default) - - - - Medium flexible - - - - Large flexible - - - - - - setShowSnackbar(false)} - duration={Snackbar.DURATION_SHORT} - > - Headline pressed - - - ); -}; - -AppbarV3Example.title = 'Appbar V3'; - -export default AppbarV3Example; - -const styles = StyleSheet.create({ - contentContainer: { - paddingVertical: 8, - }, - row: { - flexDirection: 'row', - alignItems: 'center', - justifyContent: 'space-between', - paddingVertical: 8, - paddingHorizontal: 16, - }, - customColor: { - backgroundColor: Palette.secondary80, - }, - headlineImage: { - width: 32, - height: 32, - }, -}); diff --git a/example/src/Examples/BottomNavigationExample.tsx b/example/src/Examples/BottomNavigationExample.tsx index b66bb474d6..ea5ead5ace 100644 --- a/example/src/Examples/BottomNavigationExample.tsx +++ b/example/src/Examples/BottomNavigationExample.tsx @@ -86,45 +86,53 @@ const BottomNavigationExample = () => { return ( - - navigation.goBack()} /> - - setMenuVisible(false)} - anchor={ - setMenuVisible(true)} - /> - } - > - { - setSceneAnimation(undefined); - setMenuVisible(false); - }} - title="Scene animation: none" - /> - { - setSceneAnimation('shifting'); - setMenuVisible(false); - }} - title="Scene animation: shifting" - /> - { - setSceneAnimation('opacity'); - setMenuVisible(false); - }} - title="Scene animation: opacity" - /> - - + navigation.goBack(), + }} + trailingActions={[ + { + key: 'more', + icon: MORE_ICON, + 'aria-label': 'More options', + onPress: () => setMenuVisible(true), + }, + ]} + /> + setMenuVisible(false)} + anchor={{ x: Dimensions.get('window').width - 24, y: 56 }} + > + { + setSceneAnimation(undefined); + setMenuVisible(false); + }} + title="Scene animation: none" + /> + { + setSceneAnimation('shifting'); + setMenuVisible(false); + }} + title="Scene animation: shifting" + /> + { + setSceneAnimation('opacity'); + setMenuVisible(false); + }} + title="Scene animation: opacity" + /> + { const [visible, setVisible] = React.useState({}); const [contextualMenuCoord, setContextualMenuCoor] = React.useState({ x: 0, y: 0 }); + const [appbarMenuCoord, setAppbarMenuCoord] = + React.useState({ x: 0, y: 0 }); const _toggleMenu = (name: string) => () => setVisible({ ...visible, [name]: !visible[name] }); @@ -42,6 +44,14 @@ const MenuExample = () => { setVisible({ menu3: true }); }; + const _openAppbarMenu = (event: GestureResponderEvent) => { + setAppbarMenuCoord({ + x: event.nativeEvent.pageX, + y: event.nativeEvent.pageY, + }); + setVisible({ ...visible, menu1: true }); + }; + React.useLayoutEffect(() => { navigation.setOptions({ headerShown: false, @@ -50,24 +60,35 @@ const MenuExample = () => { return ( - - navigation.goBack()} /> - - - } - > - {}} title="Undo" /> - {}} title="Redo" /> - - {}} title="Cut" disabled /> - {}} title="Copy" disabled /> - {}} title="Paste" /> - - + navigation.goBack(), + }} + trailingActions={[ + { + key: 'more', + icon: MORE_ICON, + 'aria-label': 'More options', + onPress: _openAppbarMenu, + }, + ]} + /> + + {}} title="Undo" /> + {}} title="Redo" /> + + {}} title="Cut" disabled /> + {}} title="Copy" disabled /> + {}} title="Paste" /> + { return ( - - navigation.goBack()} /> - - + navigation.goBack(), + }} + /> { React.useLayoutEffect(() => { navigation.setOptions({ header: () => ( - - - navigation.goBack()} /> - - - - {}} /> - - - {}} /> - - - {}} /> - - + navigation.goBack(), + }} + trailingActions={[ + { + key: 'print', + icon: 'printer', + 'aria-label': 'Print', + onPress: () => {}, + }, + { + key: 'search', + icon: 'magnify', + 'aria-label': 'Search', + onPress: () => {}, + }, + { + key: 'more', + icon: MORE_ICON, + 'aria-label': 'More options', + onPress: () => {}, + }, + ]} + /> ), }); }); diff --git a/example/src/RootNavigator.tsx b/example/src/RootNavigator.tsx index 95ea077275..872ef9b79e 100644 --- a/example/src/RootNavigator.tsx +++ b/example/src/RootNavigator.tsx @@ -25,18 +25,20 @@ function Header({ navigation, route, options, back }: NativeStackHeaderProps) { const drawerNavigation = useNavigation('Home'); return ( - - {back ? ( - navigation.goBack()} /> - ) : ( - drawerNavigation.openDrawer()} - /> - )} - - + navigation.goBack() } + : { + icon: 'menu', + 'aria-label': 'Open navigation menu', + onPress: () => drawerNavigation.openDrawer(), + } + } + /> ); } diff --git a/src/components/Appbar/Appbar.tsx b/src/components/Appbar/Appbar.tsx index c42304765b..46a9d00402 100644 --- a/src/components/Appbar/Appbar.tsx +++ b/src/components/Appbar/Appbar.tsx @@ -1,340 +1,451 @@ import * as React from 'react'; -import { Animated, StyleSheet, View } from 'react-native'; -import type { ColorValue, StyleProp, ViewProps, ViewStyle } from 'react-native'; +import { StyleSheet, View } from 'react-native'; +import type { ColorValue, ViewProps } from 'react-native'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; + +import AppbarButton from './AppbarButton'; import AppbarContent from './AppbarContent'; +import type { Props } from './types'; import { - getAppbarBackgroundColor, - modeAppbarHeight, - renderAppbarContent, - filterAppbarActions, + APPBAR_HEADLINE_IMAGE_HEIGHT, + APPBAR_ICON_BUTTON_SIZE, + APPBAR_SEARCH_MAX_WIDTH, + getAppbarBorders, + getAppbarHeight, + getTrailingActionsWidth, } from './utils'; -import type { AppbarModes, AppbarChildProps } from './utils'; import { useInternalTheme } from '../../core/theming'; -import type { Elevation, ThemeProp } from '../../types'; +import Searchbar from '../Searchbar'; import Surface from '../Surface'; -export type Props = Omit, 'style'> & { - /** - * Whether the background color is a dark color. A dark appbar will render light text and vice-versa. - */ - dark?: boolean; - /** - * Content of the `Appbar`. - */ - children: React.ReactNode; - /** - * @supported Available in v5.x with theme version 3 - * - * Mode of the Appbar. - * - `small` - Appbar with default height (64). - * - `medium` - Appbar with medium height (112). - * - `large` - Appbar with large height (152). - * - `center-aligned` - Appbar with default height and center-aligned title. - */ - mode?: 'small' | 'medium' | 'large' | 'center-aligned'; - /** - * @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. - */ - safeAreaInsets?: { - bottom?: number; - top?: number; - left?: number; - right?: number; - }; - /** - * @optional - */ - theme?: ThemeProp; - style?: Animated.WithAnimatedValue>; -}; +const EMPTY_TRAILING_ACTIONS = [] as const; /** - * 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 Material Design app bar for displaying a page headline, navigation, and + * contextual actions. Appbar supports small, medium flexible, large flexible, + * and search variants. Its surface color automatically changes when content + * has scrolled, and it accounts for safe-area insets. + * + * ## Variants + * + * | `variant` | Purpose | + * | --- | --- | + * | `small` | A compact 64dp app bar with a one-line headline. | + * | `medium-flexible` | A flexible app bar with a two-line headline and optional subtitle or image. | + * | `large-flexible` | A prominent flexible app bar with a two-line headline and optional subtitle or image. | + * | `search` | An app bar containing a centered Paper `Searchbar`. | * - * By default Appbar uses primary color as a background, in dark theme with `adaptive` mode it will use surface colour instead. - * See [Dark Theme](https://callstack.github.io/react-native-paper/docs/guides/theming#dark-theme) for more informations + * ## Main props + * + * | Prop | Description | + * | --- | --- | + * | `headline` | Required accessible headline for every non-search variant. | + * | `subtitle` | Optional supporting text for written headlines. | + * | `headlineAlignment` | Aligns headline content to `leading` (default) or `center`. | + * | `headlineImage` | Replaces the visible small headline, or appears above a flexible headline. Images should fit within 32dp height. | + * | `onHeadlinePress` | Makes the headline area interactive; use `headlinePressableProps` for its accessibility state. | + * | `leadingButton` | A back button (`{ type: 'back' }`) or standard icon-button configuration. | + * | `trailingActions` | Standard icon-button configurations, or exactly one `filled`/`tonal` action with optional `wide` width. Every action requires a stable `key` and `aria-label`. | + * | `searchBar` | Required for the `search` variant. Accepts Paper `Searchbar` props except `mode`, `elevation`, `showDivider`, and `theme`. | + * | `isScrolled` | Uses `surfaceContainer` instead of `surface` when content has scrolled. | + * | `safeAreaInsets` | Overrides detected top, left, or right safe-area insets. | + * | `statusBarHeight` | Overrides only the automatic top inset. | + * | `contentStyle` | Styles the headline and subtitle area. | + * | `style` | Styles the app bar and can override its background color. | + * + * ## Migrating from the compound API + * + * `Appbar.Header`, `Appbar.Content`, `Appbar.Action`, and + * `Appbar.BackAction` have been removed. Render one `Appbar` and provide its + * headline, leading button, and trailing actions as props. The former + * `mode="medium"` and `mode="large"` values are now + * `variant="medium-flexible"` and `variant="large-flexible"`; centered + * content uses `headlineAlignment="center"`. * * ## Usage - * ### Top bar + * + * ### Small app bar * ```js * import * as React from 'react'; * import { Appbar } from 'react-native-paper'; * * const MyComponent = () => ( - * - * {}} /> - * - * {}} /> - * {}} /> - * + * {} }} + * trailingActions={[ + * { + * key: 'search', + * icon: 'magnify', + * 'aria-label': 'Search', + * onPress: () => {}, + * }, + * { + * key: 'more', + * icon: 'dots-vertical', + * 'aria-label': 'More options', + * onPress: () => {}, + * }, + * ]} + * /> * ); * * export default MyComponent; * ``` * - * ### Bottom bar + * ### Flexible app bar * ```js - * import * as React from 'react'; - * import { StyleSheet } from 'react-native'; - * import { Appbar, FAB, useTheme } from 'react-native-paper'; - * import { useSafeAreaInsets } from 'react-native-safe-area-context'; - * - * const BOTTOM_APPBAR_HEIGHT = 80; - * const MEDIUM_FAB_HEIGHT = 56; - * - * const MyComponent = () => { - * const { bottom } = useSafeAreaInsets(); - * const theme = useTheme(); - * - * return ( - * - * {}} /> - * {}} /> - * {}} /> - * {}} /> - * {}} - * style={[ - * styles.fab, - * { top: (BOTTOM_APPBAR_HEIGHT - MEDIUM_FAB_HEIGHT) / 2 }, - * ]} - * /> - * - * ); - * }; - * - * const styles = StyleSheet.create({ - * bottom: { - * backgroundColor: 'aquamarine', - * position: 'absolute', - * left: 0, - * right: 0, - * bottom: 0, - * }, - * fab: { - * position: 'absolute', - * right: 16, - * }, - * }); + * + * ``` * - * export default MyComponent; + * ### Search app bar + * ```js + * {} }} + * searchBar={{ + * placeholder: 'Search messages', + * value: query, + * onChangeText: setQuery, + * }} + * /> * ``` */ const Appbar = ({ - children, - dark, - style, - mode = 'small', - elevated, + contentStyle, + headline, + headlineAlignment = 'leading', + headlineImage, + headlinePressableProps, + headlineProps, + isScrolled = false, + leadingButton, + onHeadlinePress, safeAreaInsets, + searchBar, + statusBarHeight, + style, + subtitle, + subtitleProps, + testID = 'appbar', theme: themeOverrides, + trailingActions = EMPTY_TRAILING_ACTIONS, + variant, + ref, ...rest }: Props) => { const theme = useInternalTheme(themeOverrides); - const flattenedStyle = StyleSheet.flatten(style); - const { - backgroundColor: customBackground, - elevation = elevated ? 2 : 0, - ...restStyle + const detectedInsets = useSafeAreaInsets(); + const { customBackground, restStyle, borderRadius } = React.useMemo(() => { + const flattenedStyle = StyleSheet.flatten(style); // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - } = (flattenedStyle || {}) as Exclude & { - elevation?: Elevation; - backgroundColor?: ColorValue; - }; + const resolvedStyle = (flattenedStyle || {}) as Exclude< + typeof flattenedStyle, + number + > & { + backgroundColor?: ColorValue; + }; + const { backgroundColor, ...remainingStyle } = resolvedStyle; - const backgroundColor = getAppbarBackgroundColor( - theme, - elevation, - customBackground, - elevated + return { + customBackground: backgroundColor, + restStyle: remainingStyle, + borderRadius: getAppbarBorders(remainingStyle), + }; + }, [style]); + const backgroundColor = + customBackground ?? + (isScrolled ? theme.colors.surfaceContainer : theme.colors.surface); + const hasSubtitle = typeof subtitle === 'string' && subtitle.length > 0; + const minHeight = getAppbarHeight(variant, hasSubtitle); + const topInset = statusBarHeight ?? safeAreaInsets?.top ?? detectedInsets.top; + const leftInset = safeAreaInsets?.left ?? detectedInsets.left; + const rightInset = safeAreaInsets?.right ?? detectedInsets.right; + const horizontalInset = Math.max(leftInset, rightInset); + const centered = headlineAlignment === 'center'; + const sideWidth = Math.max( + leadingButton ? APPBAR_ICON_BUTTON_SIZE : 0, + getTrailingActionsWidth(trailingActions) + ); + const sideStyle = React.useMemo(() => ({ width: sideWidth }), [sideWidth]); + const surfaceStyle = React.useMemo( + () => [ + { + backgroundColor, + paddingTop: topInset, + paddingHorizontal: horizontalInset, + }, + borderRadius, + ], + [backgroundColor, borderRadius, horizontalInset, topInset] + ); + const appbarStyle = React.useMemo( + () => [styles.appbar, { backgroundColor, minHeight }, restStyle], + [backgroundColor, minHeight, restStyle] ); + const resolvedSearchInputStyle = React.useMemo( + () => [ + searchBar?.inputStyle, + styles.searchInput, + { color: theme.colors.onSurface }, + ], + [searchBar?.inputStyle, theme.colors.onSurface] + ); + const searchBackgroundColor = isScrolled + ? theme.colors.surfaceContainerHighest + : theme.colors.surfaceContainer; + const resolvedSearchStyle = React.useMemo( + () => [ + styles.searchBar, + { backgroundColor: searchBackgroundColor }, + searchBar?.style, + ], + [searchBackgroundColor, searchBar?.style] + ); + const { + accessibilityLabel: _accessibilityLabel, + accessibilityRole: _accessibilityRole, + accessible: _accessible, + 'aria-label': _ariaLabel, + role: _role, + ...viewProps + } = rest as ViewProps; - const isMode = (modeToCompare: AppbarModes) => { - return mode === modeToCompare; - }; + const renderLeadingButton = () => + leadingButton ? ( + + ) : null; - const isDark = typeof dark === 'boolean' ? dark : false; + const renderTrailingActions = () => + trailingActions.map((action) => ( + + )); - const isCenterAlignedMode = isMode('center-aligned'); + const renderSearchAppbar = () => { + if (!searchBar) { + return null; + } - let shouldCenterContent = false; - let shouldAddLeftSpacing = false; - let shouldAddRightSpacing = false; - if (isCenterAlignedMode) { - let hasAppbarContent = false; - let leftItemsCount = 0; - let rightItemsCount = 0; + const { + inputStyle: _searchInputStyle, + style: _searchStyle, + testID: searchTestID = `${testID}-search`, + ...searchProps + } = searchBar; - React.Children.forEach(children, (child) => { - if (React.isValidElement(child)) { - const isLeading = child.props.isLeading === true; + return ( + + {renderLeadingButton()} + + + + + + {renderTrailingActions()} + + ); + }; - if (child.type === AppbarContent) { - hasAppbarContent = true; - } else if (isLeading || !hasAppbarContent) { - leftItemsCount++; - } else { - rightItemsCount++; + const contentProps = + variant !== 'search' + ? { + alignment: headlineAlignment, + contentStyle, + headline, + headlineImage, + headlinePressableProps, + headlineProps, + onHeadlinePress, + subtitle, + subtitleProps, + testID: `${testID}-content`, + theme, + variant, } - } - }); + : null; + + const renderFlexibleHeadlineImage = () => + headlineImage ? ( + + {headlineImage} + + ) : null; + + const renderSmallAppbar = () => { + if (!contentProps) { + return null; + } - shouldCenterContent = - hasAppbarContent && leftItemsCount < 2 && rightItemsCount < 3; - shouldAddLeftSpacing = shouldCenterContent && leftItemsCount === 0; - shouldAddRightSpacing = shouldCenterContent && rightItemsCount === 0; - } + if (centered || headlineImage) { + return ( + + {renderLeadingButton()} + + + {renderTrailingActions()} + + + ); + } + + return ( + + {renderLeadingButton()} + + {renderTrailingActions()} + + ); + }; - const spacingStyle = styles.v3Spacing; + const renderFlexibleAppbar = () => { + if (!contentProps) { + return null; + } - const insets = { - paddingBottom: safeAreaInsets?.bottom, - paddingTop: safeAreaInsets?.top, - paddingLeft: safeAreaInsets?.left, - paddingRight: safeAreaInsets?.right, + return ( + + {headlineImage ? ( + + + {renderLeadingButton()} + + {renderFlexibleHeadlineImage()} + + {renderTrailingActions()} + + + ) : ( + + {renderLeadingButton()} + + {renderTrailingActions()} + + + )} + + + ); }; 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} + + {variant === 'search' + ? renderSearchAppbar() + : variant === 'small' + ? renderSmallAppbar() + : renderFlexibleAppbar()} + ); }; const styles = StyleSheet.create({ appbar: { - flexDirection: 'row', - alignItems: 'center', paddingHorizontal: 4, }, - v3Spacing: { - width: 52, + smallRow: { + flex: 1, + flexDirection: 'row', + alignItems: 'center', }, - controlsRow: { + searchRow: { flex: 1, flexDirection: 'row', alignItems: 'center', + }, + searchSlot: { + flex: 1, + marginHorizontal: 8, + alignItems: 'center', + }, + searchBar: { + width: '100%', + }, + searchWidthLimiter: { + width: '100%', + maxWidth: APPBAR_SEARCH_MAX_WIDTH, + }, + searchInput: { + textAlign: 'center', + }, + flexibleContainer: { + flex: 1, + }, + controlsRow: { + minHeight: 56, + flexDirection: 'row', + alignItems: 'flex-start', justifyContent: 'space-between', }, - rightActionControls: { + trailingActions: { flexDirection: 'row', - flex: 1, justifyContent: 'flex-end', }, - columnContainer: { - flexDirection: 'column', - flex: 1, - paddingTop: 8, + side: { + flexDirection: 'row', + }, + headlineLeading: { + marginStart: 12, }, - centerAlignedContainer: { - paddingTop: 0, + headlineWithLeading: { + marginStart: 4, + }, + flexibleHeadlineImage: { + flex: 1, + height: APPBAR_HEADLINE_IMAGE_HEIGHT, + maxWidth: '100%', + marginTop: 12, + alignItems: 'center', + justifyContent: 'center', + overflow: 'hidden', }, }); -export default Appbar; +const MemoizedAppbar = React.memo(Appbar); + +export default MemoizedAppbar; // @component-docs ignore-next-line -export { Appbar }; +export { MemoizedAppbar as Appbar }; diff --git a/src/components/Appbar/AppbarAction.tsx b/src/components/Appbar/AppbarAction.tsx deleted file mode 100644 index 400271a988..0000000000 --- a/src/components/Appbar/AppbarAction.tsx +++ /dev/null @@ -1,117 +0,0 @@ -import * as React from 'react'; -import type { - Animated, - ColorValue, - StyleProp, - View, - ViewStyle, -} from 'react-native'; - -import { useInternalTheme } from '../../core/theming'; -import type { ThemeProp } from '../../types'; -import type { IconSource } from '../Icon'; -import IconButton from '../IconButton/IconButton'; - -export type Props = React.ComponentPropsWithoutRef & { - /** - * Custom color for action icon. - */ - color?: ColorValue; - /** - * Name of the icon to show. - */ - icon: IconSource; - /** - * Optional icon size. - */ - size?: number; - /** - * Whether the button is disabled. A disabled button is greyed out and `onPress` is not called on touch. - */ - disabled?: boolean; - /** - * Accessibility label for the button. This is read by the screen reader when the user taps the button. - */ - 'aria-label'?: string; - /** - * Function to execute on press. - */ - onPress?: () => void; - /** - * @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. - */ - isLeading?: boolean; - style?: Animated.WithAnimatedValue>; - ref?: React.Ref; - /** - * @optional - */ - theme?: ThemeProp; -}; - -/** - * A component used to display an action item in the appbar. - * - * ## Usage - * ```js - * import * as React from 'react'; - * import { Appbar } from 'react-native-paper'; - * import { Platform } from 'react-native'; - * - * const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical'; - * - * const MyComponent = () => ( - * - * - * {}} /> - * {}} /> - * - * ); - * - * export default MyComponent; - * ``` - */ -const AppbarAction = ({ - size = 24, - color: iconColor, - icon, - disabled, - onPress, - 'aria-label': ariaLabel, - isLeading, - theme: themeOverrides, - ref, - ...rest -}: Props) => { - const theme = useInternalTheme(themeOverrides); - const { colors } = theme; - - const actionIconColor = iconColor - ? iconColor - : isLeading - ? colors.onSurface - : colors.onSurfaceVariant; - - return ( - - ); -}; - -AppbarAction.displayName = 'Appbar.Action'; - -export default AppbarAction; - -// @component-docs ignore-next-line -export { AppbarAction }; diff --git a/src/components/Appbar/AppbarBackAction.tsx b/src/components/Appbar/AppbarBackAction.tsx deleted file mode 100644 index 2835c27c91..0000000000 --- a/src/components/Appbar/AppbarBackAction.tsx +++ /dev/null @@ -1,79 +0,0 @@ -import * as React from 'react'; -import type { - Animated, - ColorValue, - GestureResponderEvent, - StyleProp, - View, - ViewStyle, -} from 'react-native'; - -import type { $Omit } from './../../types'; -import AppbarAction from './AppbarAction'; -import AppbarBackIcon from './AppbarBackIcon'; - -export type Props = $Omit< - React.ComponentPropsWithoutRef, - 'icon' -> & { - /** - * Custom color for back icon. - */ - color?: ColorValue; - /** - * Optional icon size. - */ - size?: number; - /** - * Whether the button is disabled. A disabled button is greyed out and `onPress` is not called on touch. - */ - disabled?: boolean; - /** - * Accessibility label for the button. This is read by the screen reader when the user taps the button. - */ - 'aria-label'?: string; - /** - * Function to execute on press. - */ - onPress?: (e: GestureResponderEvent) => void; - style?: Animated.WithAnimatedValue>; - ref?: React.Ref; -}; - -/** - * A component used to display a back button in the appbar. - * - * ## Usage - * ```js - * import * as React from 'react'; - * import { Appbar } from 'react-native-paper'; - * - * const MyComponent = () => ( - * - * {}} /> - * - * ); - * - * export default MyComponent; - * ``` - */ -const AppbarBackAction = ({ - 'aria-label': ariaLabel = 'Back', - ref, - ...rest -}: Props) => ( - -); - -AppbarBackAction.displayName = 'Appbar.BackAction'; - -export default AppbarBackAction; - -// @component-docs ignore-next-line -export { AppbarBackAction }; diff --git a/src/components/AppbarV3/AppbarButton.tsx b/src/components/Appbar/AppbarButton.tsx similarity index 97% rename from src/components/AppbarV3/AppbarButton.tsx rename to src/components/Appbar/AppbarButton.tsx index b6e7d942aa..9fb694c330 100644 --- a/src/components/AppbarV3/AppbarButton.tsx +++ b/src/components/Appbar/AppbarButton.tsx @@ -1,9 +1,9 @@ import * as React from 'react'; import { StyleSheet } from 'react-native'; +import AppbarBackIcon from './AppbarBackIcon'; import type { AppbarLeadingButton, AppbarTrailingAction } from './types'; import type { Theme } from '../../types'; -import AppbarBackIcon from '../Appbar/AppbarBackIcon'; import IconButton from '../IconButton/IconButton'; type Props = { diff --git a/src/components/Appbar/AppbarContent.tsx b/src/components/Appbar/AppbarContent.tsx index 826477619d..96d8e0dee6 100644 --- a/src/components/Appbar/AppbarContent.tsx +++ b/src/components/Appbar/AppbarContent.tsx @@ -1,228 +1,216 @@ import * as React from 'react'; -import { StyleSheet, Pressable, View } from 'react-native'; -import type { - GestureResponderEvent, - StyleProp, - TextStyle, - ViewStyle, - ViewProps, -} from 'react-native'; +import { Pressable, StyleSheet, View } from 'react-native'; +import type { StyleProp, ViewStyle } from 'react-native'; -import { - modeTextVariant, - modeSubtitleTextVariant, - modeSubtitleTextSpacing, -} from './utils'; -import { useInternalTheme } from '../../core/theming'; -import type { TypescaleKey } from '../../theme/types'; -import type { $RemoveChildren, ThemeProp } from '../../types'; +import type { + AppbarHeadlineAlignment, + AppbarHeadlineVariant, + Props as AppbarProps, +} from './types'; +import { APPBAR_HEADLINE_IMAGE_HEIGHT } from './utils'; +import type { Theme, TypescaleKey } from '../../types'; import Text from '../Typography/Text'; -import type { TextRef } from '../Typography/Text'; -type TitleString = { - title: string; - titleStyle?: StyleProp; +type Props = Pick< + AppbarProps, + | 'contentStyle' + | 'headline' + | 'headlineImage' + | 'headlinePressableProps' + | 'headlineProps' + | 'onHeadlinePress' + | 'subtitle' + | 'subtitleProps' +> & { + alignment: AppbarHeadlineAlignment; + theme: Theme; + variant: AppbarHeadlineVariant; + style?: StyleProp; + testID: string; }; -type TitleElement = { title: React.ReactNode; titleStyle?: never }; +const headlineVariants: Record = { + small: 'titleLarge', + 'medium-flexible': 'headlineMedium', + 'large-flexible': 'displaySmall', +}; -export type Props = $RemoveChildren & { - // For `title` and `titleStyle` props their types are duplicated due to the generation of documentation. - // Appropriate type for them are either `TitleString` or `TitleElement`, depends on `title` type. - /** - * Text or component for the title. - */ - title: React.ReactNode; - /** - * Style for the title, if `title` is a string. - */ - titleStyle?: StyleProp; - /** - * Reference for the title. - */ - titleRef?: React.RefObject; - /** - * Text or component for the subtitle. - */ - subtitle?: React.ReactNode; - /** - * Style for the subtitle. - */ - subtitleStyle?: StyleProp; - /** - * Function to execute on press. - */ - onPress?: (e: GestureResponderEvent) => void; - /** - * If true, disable all interactions for this component. - */ - disabled?: boolean; - /** - * Custom color for the text. - */ - color?: string; - /** - * Specifies the largest possible scale a title font can reach. - */ - titleMaxFontSizeMultiplier?: number; - /** - * @internal - */ - mode?: 'small' | 'medium' | 'large' | 'center-aligned'; - style?: StyleProp; - /** - * @optional - */ - theme?: ThemeProp; - /** - * testID to be used on tests. - */ - testID?: string; -} & (TitleString | TitleElement); +const subtitleVariants: Record = { + small: 'labelMedium', + 'medium-flexible': 'labelLarge', + 'large-flexible': 'titleMedium', +}; + +const subtitleSpacing: Record = { + small: 0, + 'medium-flexible': 4, + 'large-flexible': 8, +}; -/** - * A component used to display a title and optional subtitle in an appbar. - * - * ## Usage - * ```js - * import * as React from 'react'; - * import { Appbar } from 'react-native-paper'; - * - * const MyComponent = () => ( - * - * - * - * ); - * - * export default MyComponent; - * ``` - */ const AppbarContent = ({ - color: titleColor, + alignment, + contentStyle, + headline, + headlineImage, + headlinePressableProps, + headlineProps, + onHeadlinePress, subtitle, - subtitleStyle, - onPress, - disabled, + subtitleProps, + testID, + theme, + variant, style, - titleRef, - titleStyle, - title, - titleMaxFontSizeMultiplier, - mode = 'small', - theme: themeOverrides, - testID = 'appbar-content', - ...rest }: Props) => { - const theme = useInternalTheme(themeOverrides); - const { colors, fonts } = theme; - - const titleTextColor = titleColor ? titleColor : colors.onSurface; - - const modeContainerStyles = { - small: styles.v3DefaultContainer, - medium: styles.v3MediumContainer, - large: styles.v3LargeContainer, - 'center-aligned': styles.v3DefaultContainer, - }; - - const variant = modeTextVariant[mode] as TypescaleKey; - const subtitleVariant = modeSubtitleTextVariant[mode] as TypescaleKey; - const subtitleTopPadding = modeSubtitleTextSpacing[mode]; - - const contentWrapperProps = { - pointerEvents: 'box-none', - style: [styles.container, modeContainerStyles[mode], style], - testID, - ...rest, - } satisfies ViewProps; + const headlineVariant = headlineVariants[variant]; + const subtitleVariant = subtitleVariants[variant]; + const centered = alignment === 'center'; + const hasHeadlineImage = variant === 'small' && Boolean(headlineImage); + const headlineStyle = React.useMemo( + () => [ + styles.text, + centered && styles.centeredText, + { color: theme.colors.onSurface }, + headlineProps?.style, + ], + [centered, headlineProps?.style, theme.colors.onSurface] + ); + const subtitleStyle = React.useMemo( + () => [ + styles.text, + centered && styles.centeredText, + { marginTop: subtitleSpacing[variant] }, + { color: theme.colors.onSurfaceVariant }, + subtitleProps?.style, + ], + [centered, subtitleProps?.style, theme.colors.onSurfaceVariant, variant] + ); + const wrapperStyle = React.useMemo( + () => [ + styles.container, + variant !== 'small' && styles.flexibleContainer, + centered && styles.centeredContainer, + style, + contentStyle, + ], + [centered, contentStyle, style, variant] + ); - const content = ( + const content = hasHeadlineImage ? ( + + {headlineImage} + + ) : ( <> - {typeof title === 'string' ? ( - <> - - {title} - - {subtitle ? ( - - {subtitle} - - ) : null} - - ) : ( - title - )} + + {headline} + + {subtitle ? ( + + {subtitle} + + ) : null} ); - if (onPress) { + const wrapperProps = { + testID, + style: wrapperStyle, + }; + + if (onHeadlinePress) { + const { + 'aria-label': ariaLabel, + accessibilityLabel, + disabled, + ...restHeadlinePressableProps + } = headlinePressableProps ?? {}; + return ( {content} ); } - return {content}; + return ( + + {content} + + ); }; -AppbarContent.displayName = 'Appbar.Content'; - const styles = StyleSheet.create({ container: { flex: 1, - paddingHorizontal: 12, + justifyContent: 'center', + minWidth: 0, }, - v3DefaultContainer: { - paddingHorizontal: 0, + flexibleContainer: { + flex: 0, + paddingHorizontal: 16, + paddingTop: 8, + paddingBottom: 12, }, - v3MediumContainer: { - paddingHorizontal: 0, - justifyContent: 'flex-end', - paddingBottom: 24, + centeredContainer: { + alignItems: 'center', }, - v3LargeContainer: { - paddingHorizontal: 0, - paddingTop: 36, - justifyContent: 'flex-end', - paddingBottom: 28, + text: { + alignSelf: 'stretch', + }, + centeredText: { + textAlign: 'center', + }, + headlineImage: { + height: APPBAR_HEADLINE_IMAGE_HEIGHT, + maxWidth: '100%', + alignItems: 'center', + justifyContent: 'center', + overflow: 'hidden', }, }); -export default AppbarContent; - -// @component-docs ignore-next-line -export { AppbarContent }; +export default React.memo(AppbarContent); diff --git a/src/components/Appbar/AppbarHeader.tsx b/src/components/Appbar/AppbarHeader.tsx deleted file mode 100644 index 0252cc89ba..0000000000 --- a/src/components/Appbar/AppbarHeader.tsx +++ /dev/null @@ -1,164 +0,0 @@ -import * as React from 'react'; -import { Animated, Platform, StyleSheet, View } from 'react-native'; -import type { ColorValue, StyleProp, ViewStyle } from 'react-native'; - -import { useSafeAreaInsets } from 'react-native-safe-area-context'; - -import { Appbar } from './Appbar'; -import { - getAppbarBackgroundColor, - modeAppbarHeight, - getAppbarBorders, -} from './utils'; -import { useInternalTheme } from '../../core/theming'; -import { shadow } from '../../theme/tokens/sys/elevation'; -import type { ThemeProp } from '../../types'; - -export type Props = Omit< - React.ComponentProps, - 'safeAreaInsets' -> & { - /** - * Whether the background color is a dark color. A dark header will render light text and vice-versa. - */ - dark?: boolean; - /** - * Extra padding to add at the top of header to account for translucent status bar. - * This is automatically handled on iOS >= 11 including iPhone X using `SafeAreaView`. - * If you are using Expo, we assume translucent status bar and set a height for status bar automatically. - * Pass `0` or a custom value to disable the default behaviour, and customize the height. - */ - statusBarHeight?: number; - /** - * Content of the header. - */ - children: React.ReactNode; - /** - * @supported Available in v5.x with theme version 3 - * - * Mode of the Appbar. - * - `small` - Appbar with default height (64). - * - `medium` - Appbar with medium height (112). - * - `large` - Appbar with large height (152). - * - `center-aligned` - Appbar with default height and center-aligned title. - */ - mode?: 'small' | 'medium' | 'large' | 'center-aligned'; - /** - * @supported Available in v5.x with theme version 3 - * Whether Appbar background should have the elevation along with primary color pigment. - */ - elevated?: boolean; - /** - * @optional - */ - theme?: ThemeProp; - style?: Animated.WithAnimatedValue>; -}; - -/** - * A component to use as a header at the top of the screen. - * It can contain the screen title, controls such as navigation buttons, menu button etc. - * - * ## Usage - * ```js - * import * as React from 'react'; - * import { Appbar } from 'react-native-paper'; - * - * const MyComponent = () => { - * const _goBack = () => console.log('Went back'); - * - * const _handleSearch = () => console.log('Searching'); - * - * const _handleMore = () => console.log('Shown more'); - * - * return ( - * - * - * - * - * - * - * ); - * }; - * - * export default MyComponent; - * ``` - */ -const AppbarHeader = ({ - // Don't use default props since we check it to know whether we should use SafeAreaView - statusBarHeight, - style, - dark, - mode = Platform.OS === 'ios' ? 'center-aligned' : 'small', - elevated = false, - theme: themeOverrides, - testID = 'appbar-header', - ...rest -}: Props) => { - const theme = useInternalTheme(themeOverrides); - - const flattenedStyle = StyleSheet.flatten(style); - const { - height = modeAppbarHeight[mode], - elevation = elevated ? 2 : 0, - backgroundColor: customBackground, - zIndex = elevated ? 1 : 0, - ...restStyle - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - } = (flattenedStyle || {}) as Exclude & { - height?: number; - elevation?: number; - backgroundColor?: ColorValue; - zIndex?: number; - }; - - const borderRadius = getAppbarBorders(restStyle); - - const backgroundColor = getAppbarBackgroundColor( - theme, - elevation, - customBackground, - elevated - ); - - const { top, left, right } = useSafeAreaInsets(); - - return ( - - - - ); -}; - -AppbarHeader.displayName = 'Appbar.Header'; - -const styles = StyleSheet.create({ - appbar: { - elevation: 0, - }, -}); - -export default AppbarHeader; - -// @component-docs ignore-next-line -export { AppbarHeader }; diff --git a/src/components/Appbar/index.ts b/src/components/Appbar/index.ts index 498c8761f2..d8ba839263 100644 --- a/src/components/Appbar/index.ts +++ b/src/components/Appbar/index.ts @@ -1,22 +1,16 @@ -import AppbarComponent from './Appbar'; -import AppbarAction from './AppbarAction'; -import AppbarBackAction from './AppbarBackAction'; -import AppbarContent from './AppbarContent'; -import AppbarHeader from './AppbarHeader'; - -const Appbar = Object.assign( - // @component ./Appbar.tsx - AppbarComponent, - { - // @component ./AppbarContent.tsx - Content: AppbarContent, - // @component ./AppbarAction.tsx - Action: AppbarAction, - // @component ./AppbarBackAction.tsx - BackAction: AppbarBackAction, - // @component ./AppbarHeader.tsx - Header: AppbarHeader, - } -); - -export default Appbar; +export { default } from './Appbar'; +export { Appbar } from './Appbar'; +export type { + AppbarFilledTrailingAction, + AppbarHeadlineAlignment, + AppbarHeadlinePressableProps, + AppbarHeadlineTextProps, + AppbarLeadingButton, + AppbarSearchbarProps, + AppbarStandardTrailingAction, + AppbarTextProps, + AppbarTrailingAction, + AppbarTrailingActions, + AppbarVariant, + Props, +} from './types'; diff --git a/src/components/AppbarV3/types.ts b/src/components/Appbar/types.ts similarity index 100% rename from src/components/AppbarV3/types.ts rename to src/components/Appbar/types.ts diff --git a/src/components/Appbar/utils.ts b/src/components/Appbar/utils.ts index 85c5eecc7a..f42801754c 100644 --- a/src/components/Appbar/utils.ts +++ b/src/components/Appbar/utils.ts @@ -1,58 +1,19 @@ -import React from 'react'; -import type { ColorValue, StyleProp, ViewStyle } from 'react-native'; -import { StyleSheet, Animated } from 'react-native'; +import type { Animated, ViewStyle } from 'react-native'; -import { white } from '../../theme/colors'; -import type { InternalTheme, ThemeProp } from '../../types'; +import type { AppbarTrailingAction, AppbarVariant } from './types'; -export type AppbarModes = 'small' | 'medium' | 'large' | 'center-aligned'; +export const APPBAR_ICON_BUTTON_SIZE = 48; +export const APPBAR_WIDE_ICON_BUTTON_SIZE = 64; +export const APPBAR_HEADLINE_IMAGE_HEIGHT = 32; +export const APPBAR_SEARCH_MAX_WIDTH = 720; -export type AppbarChildProps = { - isLeading?: boolean; - color: string; - style?: StyleProp; -}; - -const borderStyleProperties = [ +const borderStyleProperties: readonly (keyof ViewStyle)[] = [ 'borderRadius', 'borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomRightRadius', 'borderBottomLeftRadius', -] satisfies readonly (keyof ViewStyle)[]; - -export const getAppbarBackgroundColor = ( - theme: InternalTheme, - _elevation: number, - customBackground?: ColorValue, - elevated?: boolean -) => { - const { colors } = theme; - if (customBackground) { - return customBackground; - } - - if (elevated) { - return colors.surfaceContainer; - } - - return colors.surface; -}; - -export const getAppbarColor = ({ - color, - isDark, -}: BaseProps & { color: string }) => { - if (typeof color !== 'undefined') { - return color; - } - - if (isDark) { - return white; - } - - return undefined; -}; +]; export const getAppbarBorders = ( style: @@ -73,123 +34,29 @@ export const getAppbarBorders = ( return borders; }; -type BaseProps = { - isDark: boolean; -}; - -type RenderAppbarContentProps = BaseProps & { - children: React.ReactNode; - shouldCenterContent?: boolean; - renderOnly?: (string | boolean)[]; - renderExcept?: string[]; - mode?: AppbarModes; - theme?: ThemeProp; -}; - -const MD3_DEFAULT_APPBAR_HEIGHT = 64; - -export const modeAppbarHeight = { - small: MD3_DEFAULT_APPBAR_HEIGHT, - medium: 112, - large: 152, - 'center-aligned': MD3_DEFAULT_APPBAR_HEIGHT, -}; - -export const modeTextVariant = { - small: 'titleLarge', - medium: 'headlineSmall', - large: 'headlineMedium', - 'center-aligned': 'titleLarge', -} as const; - -export const modeSubtitleTextVariant = { - small: 'labelSmall', - medium: 'labelMedium', - large: 'labelLarge', - 'center-aligned': 'labelSmall', -} as const; - -export const modeSubtitleTextSpacing = { - small: undefined, - medium: 4, - large: 8, - 'center-aligned': undefined, -} as const satisfies Record; - -export const filterAppbarActions = ( - children: React.ReactNode, - isLeading = false +export const getAppbarHeight = ( + variant: AppbarVariant, + hasSubtitle: boolean ) => { - 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; - } + if (variant === 'search' || variant === 'small') { + return 64; + } - const props: { - color?: string; - style?: StyleProp; - mode?: AppbarModes; - theme?: ThemeProp; - } = { - theme, - color: getAppbarColor({ color: child.props.color, isDark }), - }; + if (variant === 'medium-flexible') { + return hasSubtitle ? 136 : 112; + } - // @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); - }); + return hasSubtitle ? 152 : 120; }; -const styles = StyleSheet.create({ - centerAlignedContent: { - alignItems: 'center', - }, - v3Spacing: { - marginLeft: 12, - }, -}); +export const getTrailingActionsWidth = ( + actions: readonly AppbarTrailingAction[] +) => + actions.reduce( + (width, action) => + width + + (action.variant !== 'standard' && action.width === 'wide' + ? APPBAR_WIDE_ICON_BUTTON_SIZE + : APPBAR_ICON_BUTTON_SIZE), + 0 + ); diff --git a/src/components/AppbarV3/Appbar.tsx b/src/components/AppbarV3/Appbar.tsx deleted file mode 100644 index 4d756ca44f..0000000000 --- a/src/components/AppbarV3/Appbar.tsx +++ /dev/null @@ -1,353 +0,0 @@ -import * as React from 'react'; -import { StyleSheet, View } from 'react-native'; -import type { ColorValue, ViewProps } from 'react-native'; - -import { useSafeAreaInsets } from 'react-native-safe-area-context'; - -import AppbarButton from './AppbarButton'; -import AppbarContent from './AppbarContent'; -import type { Props } from './types'; -import { - APPBAR_HEADLINE_IMAGE_HEIGHT, - APPBAR_ICON_BUTTON_SIZE, - APPBAR_SEARCH_MAX_WIDTH, - getAppbarHeight, - getTrailingActionsWidth, -} from './utils'; -import { useInternalTheme } from '../../core/theming'; -import { getAppbarBorders } from '../Appbar/utils'; -import Searchbar from '../Searchbar'; -import Surface from '../Surface'; - -const EMPTY_TRAILING_ACTIONS = [] as const; - -const Appbar = ({ - contentStyle, - headline, - headlineAlignment = 'leading', - headlineImage, - headlinePressableProps, - headlineProps, - isScrolled = false, - leadingButton, - onHeadlinePress, - safeAreaInsets, - searchBar, - statusBarHeight, - style, - subtitle, - subtitleProps, - testID = 'appbar', - theme: themeOverrides, - trailingActions = EMPTY_TRAILING_ACTIONS, - variant, - ref, - ...rest -}: Props) => { - const theme = useInternalTheme(themeOverrides); - const detectedInsets = useSafeAreaInsets(); - const { customBackground, restStyle, borderRadius } = React.useMemo(() => { - const flattenedStyle = StyleSheet.flatten(style); - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - const resolvedStyle = (flattenedStyle || {}) as Exclude< - typeof flattenedStyle, - number - > & { - backgroundColor?: ColorValue; - }; - const { backgroundColor, ...remainingStyle } = resolvedStyle; - - return { - customBackground: backgroundColor, - restStyle: remainingStyle, - borderRadius: getAppbarBorders(remainingStyle), - }; - }, [style]); - const backgroundColor = - customBackground ?? - (isScrolled ? theme.colors.surfaceContainer : theme.colors.surface); - const hasSubtitle = typeof subtitle === 'string' && subtitle.length > 0; - const minHeight = getAppbarHeight(variant, hasSubtitle); - const topInset = statusBarHeight ?? safeAreaInsets?.top ?? detectedInsets.top; - const leftInset = safeAreaInsets?.left ?? detectedInsets.left; - const rightInset = safeAreaInsets?.right ?? detectedInsets.right; - const horizontalInset = Math.max(leftInset, rightInset); - const centered = headlineAlignment === 'center'; - const sideWidth = Math.max( - leadingButton ? APPBAR_ICON_BUTTON_SIZE : 0, - getTrailingActionsWidth(trailingActions) - ); - const sideStyle = React.useMemo(() => ({ width: sideWidth }), [sideWidth]); - const surfaceStyle = React.useMemo( - () => [ - { - backgroundColor, - paddingTop: topInset, - paddingHorizontal: horizontalInset, - }, - borderRadius, - ], - [backgroundColor, borderRadius, horizontalInset, topInset] - ); - const appbarStyle = React.useMemo( - () => [styles.appbar, { backgroundColor, minHeight }, restStyle], - [backgroundColor, minHeight, restStyle] - ); - const resolvedSearchInputStyle = React.useMemo( - () => [ - searchBar?.inputStyle, - styles.searchInput, - { color: theme.colors.onSurface }, - ], - [searchBar?.inputStyle, theme.colors.onSurface] - ); - const searchBackgroundColor = isScrolled - ? theme.colors.surfaceContainerHighest - : theme.colors.surfaceContainer; - const resolvedSearchStyle = React.useMemo( - () => [ - styles.searchBar, - { backgroundColor: searchBackgroundColor }, - searchBar?.style, - ], - [searchBackgroundColor, searchBar?.style] - ); - const { - accessibilityLabel: _accessibilityLabel, - accessibilityRole: _accessibilityRole, - accessible: _accessible, - 'aria-label': _ariaLabel, - role: _role, - ...viewProps - } = rest as ViewProps; - - const renderLeadingButton = () => - leadingButton ? ( - - ) : null; - - const renderTrailingActions = () => - trailingActions.map((action) => ( - - )); - - const renderSearchAppbar = () => { - if (!searchBar) { - return null; - } - - const { - inputStyle: _searchInputStyle, - style: _searchStyle, - testID: searchTestID = `${testID}-search`, - ...searchProps - } = searchBar; - - return ( - - {renderLeadingButton()} - - - - - - {renderTrailingActions()} - - ); - }; - - const contentProps = - variant !== 'search' - ? { - alignment: headlineAlignment, - contentStyle, - headline, - headlineImage, - headlinePressableProps, - headlineProps, - onHeadlinePress, - subtitle, - subtitleProps, - testID: `${testID}-content`, - theme, - variant, - } - : null; - - const renderFlexibleHeadlineImage = () => - headlineImage ? ( - - {headlineImage} - - ) : null; - - const renderSmallAppbar = () => { - if (!contentProps) { - return null; - } - - if (centered || headlineImage) { - return ( - - {renderLeadingButton()} - - - {renderTrailingActions()} - - - ); - } - - return ( - - {renderLeadingButton()} - - {renderTrailingActions()} - - ); - }; - - const renderFlexibleAppbar = () => { - if (!contentProps) { - return null; - } - - return ( - - {headlineImage ? ( - - - {renderLeadingButton()} - - {renderFlexibleHeadlineImage()} - - {renderTrailingActions()} - - - ) : ( - - {renderLeadingButton()} - - {renderTrailingActions()} - - - )} - - - ); - }; - - return ( - - - {variant === 'search' - ? renderSearchAppbar() - : variant === 'small' - ? renderSmallAppbar() - : renderFlexibleAppbar()} - - - ); -}; - -const styles = StyleSheet.create({ - appbar: { - paddingHorizontal: 4, - }, - smallRow: { - flex: 1, - flexDirection: 'row', - alignItems: 'center', - }, - searchRow: { - flex: 1, - flexDirection: 'row', - alignItems: 'center', - }, - searchSlot: { - flex: 1, - marginHorizontal: 8, - alignItems: 'center', - }, - searchBar: { - width: '100%', - }, - searchWidthLimiter: { - width: '100%', - maxWidth: APPBAR_SEARCH_MAX_WIDTH, - }, - searchInput: { - textAlign: 'center', - }, - flexibleContainer: { - flex: 1, - }, - controlsRow: { - minHeight: 56, - flexDirection: 'row', - alignItems: 'flex-start', - justifyContent: 'space-between', - }, - trailingActions: { - flexDirection: 'row', - justifyContent: 'flex-end', - }, - side: { - flexDirection: 'row', - }, - headlineLeading: { - marginStart: 12, - }, - headlineWithLeading: { - marginStart: 4, - }, - flexibleHeadlineImage: { - flex: 1, - height: APPBAR_HEADLINE_IMAGE_HEIGHT, - maxWidth: '100%', - marginTop: 12, - alignItems: 'center', - justifyContent: 'center', - overflow: 'hidden', - }, -}); - -const MemoizedAppbar = React.memo(Appbar); - -export default MemoizedAppbar; - -// @component-docs ignore-next-line -export { MemoizedAppbar as Appbar }; diff --git a/src/components/AppbarV3/AppbarContent.tsx b/src/components/AppbarV3/AppbarContent.tsx deleted file mode 100644 index ecc54513ae..0000000000 --- a/src/components/AppbarV3/AppbarContent.tsx +++ /dev/null @@ -1,216 +0,0 @@ -import * as React from 'react'; -import { Pressable, StyleSheet, View } from 'react-native'; -import type { StyleProp, ViewStyle } from 'react-native'; - -import type { - AppbarHeadlineAlignment, - AppbarHeadlineVariant, - Props as AppbarProps, -} from './types'; -import { APPBAR_HEADLINE_IMAGE_HEIGHT } from './utils'; -import type { Theme, TypescaleKey } from '../../types'; -import Text from '../Typography/Text'; - -type Props = Pick< - AppbarProps, - | 'contentStyle' - | 'headline' - | 'headlineImage' - | 'headlinePressableProps' - | 'headlineProps' - | 'onHeadlinePress' - | 'subtitle' - | 'subtitleProps' -> & { - alignment: AppbarHeadlineAlignment; - theme: Theme; - variant: AppbarHeadlineVariant; - style?: StyleProp; - testID: string; -}; - -const headlineVariants = { - small: 'titleLarge', - 'medium-flexible': 'headlineMedium', - 'large-flexible': 'displaySmall', -} as const satisfies Record; - -const subtitleVariants = { - small: 'labelMedium', - 'medium-flexible': 'labelLarge', - 'large-flexible': 'titleMedium', -} as const satisfies Record; - -const subtitleSpacing = { - small: 0, - 'medium-flexible': 4, - 'large-flexible': 8, -} as const satisfies Record; - -const AppbarContent = ({ - alignment, - contentStyle, - headline, - headlineImage, - headlinePressableProps, - headlineProps, - onHeadlinePress, - subtitle, - subtitleProps, - testID, - theme, - variant, - style, -}: Props) => { - const headlineVariant = headlineVariants[variant]; - const subtitleVariant = subtitleVariants[variant]; - const centered = alignment === 'center'; - const hasHeadlineImage = variant === 'small' && Boolean(headlineImage); - const headlineStyle = React.useMemo( - () => [ - styles.text, - centered && styles.centeredText, - { color: theme.colors.onSurface }, - headlineProps?.style, - ], - [centered, headlineProps?.style, theme.colors.onSurface] - ); - const subtitleStyle = React.useMemo( - () => [ - styles.text, - centered && styles.centeredText, - { marginTop: subtitleSpacing[variant] }, - { color: theme.colors.onSurfaceVariant }, - subtitleProps?.style, - ], - [centered, subtitleProps?.style, theme.colors.onSurfaceVariant, variant] - ); - const wrapperStyle = React.useMemo( - () => [ - styles.container, - variant !== 'small' && styles.flexibleContainer, - centered && styles.centeredContainer, - style, - contentStyle, - ], - [centered, contentStyle, style, variant] - ); - - const content = hasHeadlineImage ? ( - - {headlineImage} - - ) : ( - <> - - {headline} - - {subtitle ? ( - - {subtitle} - - ) : null} - - ); - - const wrapperProps = { - testID, - style: wrapperStyle, - }; - - if (onHeadlinePress) { - const { - 'aria-label': ariaLabel, - accessibilityLabel, - disabled, - ...restHeadlinePressableProps - } = headlinePressableProps ?? {}; - - return ( - - {content} - - ); - } - - return ( - - {content} - - ); -}; - -const styles = StyleSheet.create({ - container: { - flex: 1, - justifyContent: 'center', - minWidth: 0, - }, - flexibleContainer: { - flex: 0, - paddingHorizontal: 16, - paddingTop: 8, - paddingBottom: 12, - }, - centeredContainer: { - alignItems: 'center', - }, - text: { - alignSelf: 'stretch', - }, - centeredText: { - textAlign: 'center', - }, - headlineImage: { - height: APPBAR_HEADLINE_IMAGE_HEIGHT, - maxWidth: '100%', - alignItems: 'center', - justifyContent: 'center', - overflow: 'hidden', - }, -}); - -export default React.memo(AppbarContent); diff --git a/src/components/AppbarV3/index.ts b/src/components/AppbarV3/index.ts deleted file mode 100644 index d8ba839263..0000000000 --- a/src/components/AppbarV3/index.ts +++ /dev/null @@ -1,16 +0,0 @@ -export { default } from './Appbar'; -export { Appbar } from './Appbar'; -export type { - AppbarFilledTrailingAction, - AppbarHeadlineAlignment, - AppbarHeadlinePressableProps, - AppbarHeadlineTextProps, - AppbarLeadingButton, - AppbarSearchbarProps, - AppbarStandardTrailingAction, - AppbarTextProps, - AppbarTrailingAction, - AppbarTrailingActions, - AppbarVariant, - Props, -} from './types'; diff --git a/src/components/AppbarV3/utils.ts b/src/components/AppbarV3/utils.ts deleted file mode 100644 index 4677ffc43c..0000000000 --- a/src/components/AppbarV3/utils.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type { AppbarTrailingAction, AppbarVariant } from './types'; - -export const APPBAR_ICON_BUTTON_SIZE = 48; -export const APPBAR_WIDE_ICON_BUTTON_SIZE = 64; -export const APPBAR_HEADLINE_IMAGE_HEIGHT = 32; -export const APPBAR_SEARCH_MAX_WIDTH = 720; - -export const getAppbarHeight = ( - variant: AppbarVariant, - hasSubtitle: boolean -) => { - if (variant === 'search' || variant === 'small') { - return 64; - } - - if (variant === 'medium-flexible') { - return hasSubtitle ? 136 : 112; - } - - return hasSubtitle ? 152 : 120; -}; - -export const getTrailingActionsWidth = ( - actions: readonly AppbarTrailingAction[] -) => - actions.reduce( - (width, action) => - width + - (action.variant !== 'standard' && action.width === 'wide' - ? APPBAR_WIDE_ICON_BUTTON_SIZE - : APPBAR_ICON_BUTTON_SIZE), - 0 - ); diff --git a/src/components/__tests__/Appbar/Appbar.test.tsx b/src/components/__tests__/Appbar/Appbar.test.tsx index e18fc08671..117a479ea2 100644 --- a/src/components/__tests__/Appbar/Appbar.test.tsx +++ b/src/components/__tests__/Appbar/Appbar.test.tsx @@ -1,486 +1,725 @@ -import { Animated } from 'react-native'; +import * as React from 'react'; +import { Text, View } from 'react-native'; import { describe, expect, it, jest } from '@jest/globals'; -import { act } from '@testing-library/react-native'; import { SafeAreaProvider } from 'react-native-safe-area-context'; import { getTheme } from '../../../core/theming'; -import { render, screen } from '../../../test-utils'; -import { tokens } from '../../../theme/tokens'; +import { render, screen, userEvent } from '../../../test-utils'; import Appbar from '../../Appbar'; -import { - getAppbarBackgroundColor, - getAppbarBorders, - modeTextVariant, - renderAppbarContent as utilRenderAppbarContent, -} from '../../Appbar/utils'; -import Menu from '../../Menu/Menu'; -import Searchbar from '../../Searchbar'; -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 = ( +import type { AppbarVariant } from '../../Appbar'; + +const writtenHeadlineVariants: Exclude[] = [ + 'small', + 'medium-flexible', + 'large-flexible', +]; + +const decorativeHeadlineImage = ( + + + + Brand words + + +); + +describe('Appbar content', () => { + it.each([ + { + variant: 'small', + headlineVariant: 'titleLarge', + headlineLines: 1, + subtitleVariant: 'labelMedium', + subtitleSpacing: 0, + }, + { + variant: 'medium-flexible', + headlineVariant: 'headlineMedium', + headlineLines: 2, + subtitleVariant: 'labelLarge', + subtitleSpacing: 4, + }, + { + variant: 'large-flexible', + headlineVariant: 'displaySmall', + headlineLines: 2, + subtitleVariant: 'titleMedium', + subtitleSpacing: 8, + }, + ] as const)( + 'uses the $variant content treatment', + async ({ + variant, + headlineVariant, + headlineLines, + subtitleVariant, + subtitleSpacing, + }) => { await render( - - - - ) - ).toJSON(); + + ); - expect(tree).toMatchSnapshot(); - }); + expect(screen.getByTestId('appbar-content-headline-text')).toHaveStyle( + getTheme().fonts[headlineVariant] + ); + expect(screen.getByTestId('appbar-content-headline-text')).toHaveProp( + 'numberOfLines', + headlineLines + ); + expect(screen.getByTestId('appbar-content-subtitle-text')).toHaveStyle({ + ...getTheme().fonts[subtitleVariant], + color: getTheme().colors.onSurfaceVariant, + marginTop: subtitleSpacing, + }); + } + ); - it('passes additional props to AppbarBackAction, AppbarContent and AppbarAction', async () => { - const tree = ( - await render( - - {}} /> - - {}} /> - - ) - ).toJSON(); - - expect(tree).toMatchSnapshot(); - }); -}); + it('centers text and balances asymmetric controls for centered and image layouts', async () => { + const { rerender } = await render( + + ); -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, + expect(screen.getByTestId('appbar-content-headline-text')).toHaveStyle({ + textAlign: 'center', }); - - expect(result).toHaveLength(4); - }); - - 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', - ], + expect(screen.getByTestId('appbar-content-subtitle-text')).toHaveStyle({ + textAlign: 'center', }); + expect( + screen.getByTestId('leading-action-container-outer-layer').parent + ).toHaveStyle({ width: 96 }); + expect( + screen.getByTestId('trailing-action-container-outer-layer').parent + ).toHaveStyle({ width: 96 }); + + await rerender( + } + leadingButton={{ + type: 'back', + testID: 'leading-action', + }} + trailingActions={[ + { + key: 'more', + icon: 'dots-vertical', + 'aria-label': 'More options', + testID: 'trailing-action', + }, + { + key: 'search', + icon: 'magnify', + 'aria-label': 'Search inbox', + }, + ]} + /> + ); - expect(result).toHaveLength(3); + expect( + screen.getByTestId('leading-action-container-outer-layer').parent + ).toHaveStyle({ width: 96 }); + expect( + screen.getByTestId('trailing-action-container-outer-layer').parent + ).toHaveStyle({ width: 96 }); + expect( + screen.getByTestId('brand-mark', { includeHiddenElements: true }) + ).toBeOnTheScreen(); }); - it('should render only children types specifed in renderOnly', () => { - const result = renderAppbarContent({ - children, - isDark: false, - renderOnly: ['Appbar.Action'], - }); - - expect(result).toHaveLength(2); - }); + it('adjusts leading headline spacing when a leading button is present', async () => { + const { rerender } = await render( + + ); - it('should render AppbarContent with correct mode', () => { - const result = renderAppbarContent({ - children, - isDark: false, - renderOnly: ['Appbar.Content'], - mode: 'large', + expect(screen.getByTestId('appbar-content')).toHaveStyle({ + marginStart: 12, }); - // 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 rerender( + + ); - it('should render centered AppbarContent', () => { - const result = renderAppbarContent({ - children, - isDark: false, - renderOnly: ['Appbar.Content'], - mode: 'center-aligned', - shouldCenterContent: true, + expect(screen.getByTestId('appbar-content')).toHaveStyle({ + marginStart: 4, }); + }); +}); - const centerAlignedContent = { - alignItems: 'center', - }; - - // 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)]) +describe('Appbar surface', () => { + it('uses scroll container colors unless a custom background is supplied', async () => { + const customBackground = 'rebeccapurple'; + const { rerender } = await render( + ); - }); - it('should render AppbarContent with correct spacings', () => { - const renderResult = (withAppbarBackAction = false) => - renderAppbarContent({ - children, - isDark: false, - renderOnly: [ - 'Appbar.Content', - withAppbarBackAction && 'Appbar.BackAction', - ], - }); + expect(screen.getByTestId('appbar-root-layer')).toHaveStyle({ + backgroundColor: getTheme().colors.surface, + }); - const v3Spacing = { - marginLeft: 12, - }; + await rerender(); - // 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)]) - ); - }); + expect(screen.getByTestId('appbar-root-layer')).toHaveStyle({ + backgroundColor: getTheme().colors.surfaceContainer, + }); - it('Is recognized as a heading when no onPress callback has been passed', async () => { - await render( - - - - - + await rerender( + ); - expect(screen.getByRole('heading')).toBeOnTheScreen(); + expect(screen.getByTestId('appbar-root-layer')).toHaveStyle({ + backgroundColor: customBackground, + }); }); - it('is recognized as a button when onPress callback has been passed', async () => { - await render( - - - {}} /> - - - ); - expect(screen.getByRole('button')).toBeEnabled(); - expect(screen.queryByRole('heading')).not.toBeOnTheScreen(); - }); - it('is recognized as a disabled button when onPress and disabled is passed', async () => { + it('applies border clipping and resolves safe-area overrides on the surface', async () => { await render( - - - {}} disabled /> - + + ); - expect(screen.getByRole('button')).toBeDisabled(); - expect(screen.queryByRole('heading')).not.toBeOnTheScreen(); + expect(screen.getByTestId('appbar-root-layer')).toHaveStyle({ + borderBottomLeftRadius: 16, + borderBottomRightRadius: 16, + paddingTop: 20, + paddingHorizontal: 12, + }); }); }); -describe('AppbarAction', () => { - it('should be rendered with default theme color', async () => { - await render( - - - +describe('Appbar actions', () => { + it('skips rendering unchanged action configurations', async () => { + const icon = jest.fn(() => ); + const { rerender } = await render( + ); - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - const appbarActionIcon = screen.getByTestId('cross-fade-icon-current').props - .children; - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - expect(appbarActionIcon.props.color).toBe( - getTheme().colors.onSurfaceVariant + const initialRenderCount = icon.mock.calls.length; + + await rerender( + ); - }); - it('should be rendered with specific theme color if is leading', async () => { - await render( - - - - ); - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - const appbarActionIcon = screen.getByTestId('cross-fade-icon-current').props - .children; - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - expect(appbarActionIcon.props.color).toBe(getTheme().colors.onSurface); + expect(screen.getByTestId('stable-action-icon')).toBeOnTheScreen(); + expect(icon).toHaveBeenCalledTimes(initialRenderCount); }); - it('should be rendered with custom color', async () => { + it('maps leading, trailing, and custom action colors', async () => { await render( - - - + ( + + ), + 'aria-label': 'Navigation', + }} + trailingActions={[ + { + key: 'default', + icon: ({ color }) => ( + + ), + 'aria-label': 'Default action', + }, + { + key: 'custom', + icon: ({ color }) => ( + + ), + 'aria-label': 'Custom action', + color: 'rebeccapurple', + }, + ]} + /> ); - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - const appbarActionIcon = screen.getByTestId('cross-fade-icon-current').props - .children; - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - expect(appbarActionIcon.props.color).toBe('purple'); - }); - it('should render AppbarBackAction with custom color', async () => { - await render( - - - - ); - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - const appbarBackActionIcon = screen.getByTestId('cross-fade-icon-current') - .props.children; - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - expect(appbarBackActionIcon.props.color).toBe('purple'); + expect(screen.getByTestId('leading-icon-color')).toHaveStyle({ + backgroundColor: getTheme().colors.onSurface, + }); + expect(screen.getByTestId('trailing-icon-color')).toHaveStyle({ + backgroundColor: getTheme().colors.onSurfaceVariant, + }); + expect(screen.getByTestId('custom-icon-color')).toHaveStyle({ + backgroundColor: 'rebeccapurple', + }); }); -}); -describe('AppbarContent', () => { - (['small', 'medium', 'large', 'center-aligned'] as const).forEach((mode) => - it(`should render text component with appropriate variant for ${mode} mode`, async () => { + it.each([ + { variant: 'filled', color: getTheme().colors.primary }, + { variant: 'tonal', color: getTheme().colors.secondaryContainer }, + ] as const)( + 'maps $variant actions to their selected container color', + async ({ variant, color }) => { await render( - - - + ); - expect(screen.getByTestId('appbar-content-title-text')).toHaveStyle( - getTheme().fonts[modeTextVariant[mode]] - ); - }) + expect(screen.getByTestId('expressive-action-container')).toHaveStyle({ + backgroundColor: color, + }); + expect( + screen.getByTestId('expressive-action-container-outer-layer') + ).toHaveStyle({ width: 56 }); + } ); +}); - it('should render component passed to title', async () => { - await render( - - - Title - - } - /> - +describe('Appbar search', () => { + it('uses the placeholder as the searchbox label unless an explicit label is supplied', async () => { + const { rerender } = await render( + ); - expect(screen.getByText('Title')).toBeOnTheScreen(); - }); + expect( + screen.getByRole('searchbox', { name: 'Search messages' }) + ).toBeOnTheScreen(); + expect(screen.getByTestId('appbar-search-container')).toHaveStyle({ + backgroundColor: getTheme().colors.surfaceContainer, + }); - it('should render subtitle with MD3 typography and color tokens', async () => { - await render( - - - + await rerender( + ); - expect(screen.getByTestId('appbar-content-subtitle-text')).toHaveStyle({ - ...getTheme().fonts.labelSmall, - color: getTheme().colors.onSurfaceVariant, - }); + expect( + screen.getByRole('searchbox', { name: 'Message search' }) + ).toBeOnTheScreen(); }); - it('should apply a custom subtitle style', async () => { - const customSubtitleColor = getTheme().colors.error; - - await render( - - { + const onChangeText = jest.fn(); + const SearchAppbar = () => { + const [value, setValue] = React.useState(''); + + return ( + { + setValue(nextValue); + onChangeText(nextValue); + }, + testID: 'message-search', + }} + trailingActions={[ + { + key: 'more', + icon: 'dots-vertical', + 'aria-label': 'More options', + }, + ]} /> - + ); + }; + + await render(); + + const searchbox = screen.getByRole('searchbox', { + name: 'Search messages', + }); + expect(searchbox).toHaveStyle({ + color: getTheme().colors.onSurface, + textAlign: 'center', + }); + expect(searchbox).toHaveProp( + 'placeholderTextColor', + getTheme().colors.onSurfaceVariant ); + expect(screen.getByTestId('message-search-container')).toHaveStyle({ + backgroundColor: getTheme().colors.surfaceContainerHighest, + }); + expect( + screen.getByRole('button', { name: 'Navigate back' }) + ).toBeOnTheScreen(); + expect( + screen.getByRole('button', { name: 'More options' }) + ).toBeOnTheScreen(); - expect(screen.getByTestId('appbar-content-subtitle-text')).toHaveStyle({ - color: customSubtitleColor, + await userEvent.type(searchbox, 'draft'); + expect(onChangeText).toHaveBeenLastCalledWith('draft'); + expect(searchbox).toHaveProp('value', 'draft'); + + expect( + screen.getByTestId('message-search-container-outer-layer') + ).toHaveStyle({ width: '100%' }); + expect(screen.getByTestId('appbar-search-width-limiter')).toHaveStyle({ + width: '100%', + maxWidth: 720, }); }); }); -describe('getAppbarColors', () => { - const elevation = 4; - const customBackground = 'aquamarine'; +describe('Appbar accessibility', () => { + it.each(writtenHeadlineVariants)( + 'exposes a written %s headline as a heading', + async (variant) => { + await render(); - it('should return custom color no matter what is the theme version', () => { - expect( - getAppbarBackgroundColor(getTheme(), elevation, customBackground) - ).toBe(customBackground); - }); + expect(screen.getByRole('heading', { name: 'Inbox' })).toBeOnTheScreen(); + } + ); - it('should return v3 light color if theme version is 3', () => { - expect(getAppbarBackgroundColor(getTheme(), elevation)).toBe( - tokens.md.ref.palette.neutral98 + it('hides a small headline image behind one named heading', async () => { + await render( + ); + + expect(screen.getAllByRole('heading')).toHaveLength(1); + expect(screen.getByRole('heading', { name: 'Inbox' })).toBeOnTheScreen(); + expect(screen.queryByRole('img')).not.toBeOnTheScreen(); + expect(screen.queryByText('Brand words')).not.toBeOnTheScreen(); }); - it('should return v3 dark color if theme version is 3', () => { - expect(getAppbarBackgroundColor(getTheme(true), elevation)).toBe( - tokens.md.ref.palette.neutral6 + it.each(['medium-flexible', 'large-flexible'] as const)( + 'does not expose duplicate content for a %s headline image', + async (variant) => { + await render( + + ); + + expect(screen.getAllByRole('heading', { name: 'Inbox' })).toHaveLength(1); + expect(screen.queryByRole('img')).not.toBeOnTheScreen(); + expect(screen.queryByLabelText('Brand artwork')).not.toBeOnTheScreen(); + } + ); + + it('exposes a pressable written headline as a named button and heading', async () => { + const onHeadlinePress = jest.fn(); + await render( + ); + + expect(screen.getByRole('button', { name: 'Inbox' })).toBeOnTheScreen(); + expect(screen.getByRole('heading', { name: 'Inbox' })).toBeOnTheScreen(); }); -}); -describe('animated value changes correctly', () => { - it('appbar animated value changes correctly', async () => { - const value = new Animated.Value(1); + it('does not invoke a disabled headline action', async () => { + const onHeadlinePress = jest.fn(); await render( - - - + ); - expect(screen.getByTestId('appbar-outer-layer')).toHaveStyle({ - transform: [{ scale: 1 }], - }); - Animated.timing(value, { - toValue: 1.5, - useNativeDriver: false, - duration: 200, - }).start(); - - await act(() => { - jest.advanceTimersByTime(200); + const headlineButton = screen.getByRole('button', { + name: 'Inbox', + disabled: true, }); + await userEvent.press(headlineButton); - expect(screen.getByTestId('appbar-outer-layer')).toHaveStyle({ - transform: [{ scale: 1.5 }], - }); + expect(onHeadlinePress).not.toHaveBeenCalled(); }); - it('action animated value changes correctly', async () => { - const value = new Animated.Value(1); + it('names a pressable small headline image from its fallback headline', async () => { await render( - - - + {}} + /> ); - expect( - screen.getByTestId('appbar-action-container-outer-layer') - ).toHaveStyle({ - transform: [{ scale: 1 }], - }); - Animated.timing(value, { - toValue: 1.5, - useNativeDriver: false, - duration: 200, - }).start(); + expect(screen.getByRole('button', { name: 'Inbox' })).toBeOnTheScreen(); + }); + + it('forwards custom headline button accessibility props', async () => { + const onAccessibilityAction = jest.fn(); + await render( + {}} + headlinePressableProps={{ + accessibilityActions: [{ name: 'activate', label: 'Open inbox' }], + accessibilityHint: 'Opens the inbox menu', + accessibilityLabel: 'Inbox options', + accessibilityState: { busy: true, expanded: true }, + accessibilityValue: { text: 'Unread messages available' }, + onAccessibilityAction, + }} + /> + ); - await act(() => { - jest.advanceTimersByTime(200); + const titleButton = screen.getByRole('button', { + name: 'Inbox options', + busy: true, + expanded: true, }); - expect( - screen.getByTestId('appbar-action-container-outer-layer') - ).toHaveStyle({ - transform: [{ scale: 1.5 }], + expect(titleButton).toHaveProp( + 'accessibilityActions', + expect.arrayContaining([ + expect.objectContaining({ name: 'activate', label: 'Open inbox' }), + ]) + ); + expect(titleButton).toHaveProp('accessibilityHint', 'Opens the inbox menu'); + expect(titleButton).toHaveAccessibilityValue({ + text: 'Unread messages available', }); + expect(titleButton).toHaveProp( + 'onAccessibilityAction', + onAccessibilityAction + ); }); - it('back action animated value changes correctly', async () => { - const value = new Animated.Value(1); + it('uses default and custom labels for back buttons', async () => { await render( - - + + - + ); - expect( - screen.getByTestId('appbar-back-action-container-outer-layer') - ).toHaveStyle({ - transform: [{ scale: 1 }], - }); - - Animated.timing(value, { - toValue: 1.5, - useNativeDriver: false, - duration: 200, - }).start(); - - await act(() => { - jest.advanceTimersByTime(200); - }); + expect(screen.getByRole('button', { name: 'Back' })).toBeOnTheScreen(); expect( - screen.getByTestId('appbar-back-action-container-outer-layer') - ).toHaveStyle({ - transform: [{ scale: 1.5 }], - }); + screen.getByRole('button', { name: 'Return to inbox' }) + ).toBeOnTheScreen(); }); - it('header animated value changes correctly', async () => { - const value = new Animated.Value(1); + it('preserves trailing action labels, hints, disabled state, and busy state', async () => { await render( - - - {null} - - + ); - expect(screen.getByTestId('appbar-header-outer-layer')).toHaveStyle({ - transform: [{ scale: 1 }], - }); - - Animated.timing(value, { - toValue: 1.5, - useNativeDriver: false, - duration: 200, - }).start(); - await act(() => { - jest.advanceTimersByTime(200); + const trailingAction = screen.getByRole('button', { + name: 'Save message', + busy: true, + disabled: true, }); - expect(screen.getByTestId('appbar-header-outer-layer')).toHaveStyle({ - transform: [{ scale: 1.5 }], - }); + expect(trailingAction).toHaveProp( + 'accessibilityHint', + 'Saves the current draft' + ); + expect(trailingAction).toBeDisabled(); + expect(trailingAction).toBeBusy(); }); - it('header bottom border radius applied correctly', async () => { - const style = { borderBottomLeftRadius: 16, borderBottomRightRadius: 16 }; + it.each(['small', 'medium-flexible'] as const)( + 'hides decorative descendants of a %s headline image', + async (variant) => { + await render( + variant === 'small' ? ( + + ) : ( + + ) + ); + + const imageContainer = screen.getByTestId( + 'appbar-content-headline-image', + { includeHiddenElements: true } + ); + + expect(imageContainer).toHaveProp('aria-hidden', true); + expect(imageContainer).toHaveProp( + 'importantForAccessibility', + 'no-hide-descendants' + ); + expect( + screen.queryByRole('heading', { name: 'Brand words' }) + ).not.toBeOnTheScreen(); + } + ); + it('exposes the leading button, headline, and trailing actions in source order', async () => { await render( - - - {null} - - + ); - expect(screen.getByTestId('appbar-header-root-layer')).toHaveStyle(style); - }); - describe('getAppbarBorders', () => { - const style = { borderRadius: 10, height: 60, top: 13 }; + expect(screen.getAllByRole(/button|heading/)).toEqual([ + screen.getByRole('button', { name: 'Navigate back' }), + screen.getByRole('heading', { name: 'Inbox' }), + screen.getByRole('button', { name: 'Search inbox' }), + screen.getByRole('button', { name: 'More options' }), + ]); + }); - it('should return only border radius styles', () => { - expect(getAppbarBorders(style)).toEqual({ borderRadius: 10 }); + it('does not remount a surviving trailing action when its configuration changes', async () => { + const { rerender } = await render( + + ); + const survivingTrailingAction = screen.getByRole('button', { + name: 'Keep action', }); - it('should return empty object if no borders are passed', () => { - const style = { height: 60, top: 13 }; - expect(getAppbarBorders(style)).toEqual({}); - }); + await rerender( + + ); + + expect(screen.getByRole('button', { name: 'Keep action' })).toBe( + survivingTrailingAction + ); }); }); diff --git a/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap b/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap deleted file mode 100644 index 59c778e4be..0000000000 --- a/src/components/__tests__/Appbar/__snapshots__/Appbar.test.tsx.snap +++ /dev/null @@ -1,881 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Appbar does not pass any additional props to Searchbar 1`] = ` - - - - - - - - - - magnify - - - - - - - - - - - - - close - - - - - - - - - - -`; - -exports[`Appbar passes additional props to AppbarBackAction, AppbarContent and AppbarAction 1`] = ` - - - - - - - - - - - - - - - - - - - - Examples - - - - - - - - - - menu - - - - - - - - - -`; diff --git a/src/components/__tests__/AppbarV3/utils.test.ts b/src/components/__tests__/Appbar/utils.test.ts similarity index 98% rename from src/components/__tests__/AppbarV3/utils.test.ts rename to src/components/__tests__/Appbar/utils.test.ts index d37a585372..dff18b2684 100644 --- a/src/components/__tests__/AppbarV3/utils.test.ts +++ b/src/components/__tests__/Appbar/utils.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from '@jest/globals'; -import { getAppbarHeight, getTrailingActionsWidth } from '../../AppbarV3/utils'; +import { getAppbarHeight, getTrailingActionsWidth } from '../../Appbar/utils'; describe('getAppbarHeight', () => { it.each([ diff --git a/src/components/__tests__/AppbarV3/AppbarV3.test.tsx b/src/components/__tests__/AppbarV3/AppbarV3.test.tsx deleted file mode 100644 index fc0ceb397b..0000000000 --- a/src/components/__tests__/AppbarV3/AppbarV3.test.tsx +++ /dev/null @@ -1,725 +0,0 @@ -import * as React from 'react'; -import { Text, View } from 'react-native'; - -import { describe, expect, it, jest } from '@jest/globals'; -import { SafeAreaProvider } from 'react-native-safe-area-context'; - -import { getTheme } from '../../../core/theming'; -import { render, screen, userEvent } from '../../../test-utils'; -import AppbarV3 from '../../AppbarV3'; -import type { AppbarVariant } from '../../AppbarV3'; - -const writtenHeadlineVariants: Exclude[] = [ - 'small', - 'medium-flexible', - 'large-flexible', -]; - -const decorativeHeadlineImage = ( - - - - Brand words - - -); - -describe('AppbarV3 content', () => { - it.each([ - { - variant: 'small', - headlineVariant: 'titleLarge', - headlineLines: 1, - subtitleVariant: 'labelMedium', - subtitleSpacing: 0, - }, - { - variant: 'medium-flexible', - headlineVariant: 'headlineMedium', - headlineLines: 2, - subtitleVariant: 'labelLarge', - subtitleSpacing: 4, - }, - { - variant: 'large-flexible', - headlineVariant: 'displaySmall', - headlineLines: 2, - subtitleVariant: 'titleMedium', - subtitleSpacing: 8, - }, - ] as const)( - 'uses the $variant content treatment', - async ({ - variant, - headlineVariant, - headlineLines, - subtitleVariant, - subtitleSpacing, - }) => { - await render( - - ); - - expect(screen.getByTestId('appbar-content-headline-text')).toHaveStyle( - getTheme().fonts[headlineVariant] - ); - expect(screen.getByTestId('appbar-content-headline-text')).toHaveProp( - 'numberOfLines', - headlineLines - ); - expect(screen.getByTestId('appbar-content-subtitle-text')).toHaveStyle({ - ...getTheme().fonts[subtitleVariant], - color: getTheme().colors.onSurfaceVariant, - marginTop: subtitleSpacing, - }); - } - ); - - it('centers text and balances asymmetric controls for centered and image layouts', async () => { - const { rerender } = await render( - - ); - - expect(screen.getByTestId('appbar-content-headline-text')).toHaveStyle({ - textAlign: 'center', - }); - expect(screen.getByTestId('appbar-content-subtitle-text')).toHaveStyle({ - textAlign: 'center', - }); - expect( - screen.getByTestId('leading-action-container-outer-layer').parent - ).toHaveStyle({ width: 96 }); - expect( - screen.getByTestId('trailing-action-container-outer-layer').parent - ).toHaveStyle({ width: 96 }); - - await rerender( - } - leadingButton={{ - type: 'back', - testID: 'leading-action', - }} - trailingActions={[ - { - key: 'more', - icon: 'dots-vertical', - 'aria-label': 'More options', - testID: 'trailing-action', - }, - { - key: 'search', - icon: 'magnify', - 'aria-label': 'Search inbox', - }, - ]} - /> - ); - - expect( - screen.getByTestId('leading-action-container-outer-layer').parent - ).toHaveStyle({ width: 96 }); - expect( - screen.getByTestId('trailing-action-container-outer-layer').parent - ).toHaveStyle({ width: 96 }); - expect( - screen.getByTestId('brand-mark', { includeHiddenElements: true }) - ).toBeOnTheScreen(); - }); - - it('adjusts leading headline spacing when a leading button is present', async () => { - const { rerender } = await render( - - ); - - expect(screen.getByTestId('appbar-content')).toHaveStyle({ - marginStart: 12, - }); - - await rerender( - - ); - - expect(screen.getByTestId('appbar-content')).toHaveStyle({ - marginStart: 4, - }); - }); -}); - -describe('AppbarV3 surface', () => { - it('uses scroll container colors unless a custom background is supplied', async () => { - const customBackground = 'rebeccapurple'; - const { rerender } = await render( - - ); - - expect(screen.getByTestId('appbar-root-layer')).toHaveStyle({ - backgroundColor: getTheme().colors.surface, - }); - - await rerender(); - - expect(screen.getByTestId('appbar-root-layer')).toHaveStyle({ - backgroundColor: getTheme().colors.surfaceContainer, - }); - - await rerender( - - ); - - expect(screen.getByTestId('appbar-root-layer')).toHaveStyle({ - backgroundColor: customBackground, - }); - }); - - it('applies border clipping and resolves safe-area overrides on the surface', async () => { - await render( - - - - ); - - expect(screen.getByTestId('appbar-root-layer')).toHaveStyle({ - borderBottomLeftRadius: 16, - borderBottomRightRadius: 16, - paddingTop: 20, - paddingHorizontal: 12, - }); - }); -}); - -describe('AppbarV3 actions', () => { - it('skips rendering unchanged action configurations', async () => { - const icon = jest.fn(() => ); - const { rerender } = await render( - - ); - const initialRenderCount = icon.mock.calls.length; - - await rerender( - - ); - - expect(screen.getByTestId('stable-action-icon')).toBeOnTheScreen(); - expect(icon).toHaveBeenCalledTimes(initialRenderCount); - }); - - it('maps leading, trailing, and custom action colors', async () => { - await render( - ( - - ), - 'aria-label': 'Navigation', - }} - trailingActions={[ - { - key: 'default', - icon: ({ color }) => ( - - ), - 'aria-label': 'Default action', - }, - { - key: 'custom', - icon: ({ color }) => ( - - ), - 'aria-label': 'Custom action', - color: 'rebeccapurple', - }, - ]} - /> - ); - - expect(screen.getByTestId('leading-icon-color')).toHaveStyle({ - backgroundColor: getTheme().colors.onSurface, - }); - expect(screen.getByTestId('trailing-icon-color')).toHaveStyle({ - backgroundColor: getTheme().colors.onSurfaceVariant, - }); - expect(screen.getByTestId('custom-icon-color')).toHaveStyle({ - backgroundColor: 'rebeccapurple', - }); - }); - - it.each([ - { variant: 'filled', color: getTheme().colors.primary }, - { variant: 'tonal', color: getTheme().colors.secondaryContainer }, - ] as const)( - 'maps $variant actions to their selected container color', - async ({ variant, color }) => { - await render( - - ); - - expect(screen.getByTestId('expressive-action-container')).toHaveStyle({ - backgroundColor: color, - }); - expect( - screen.getByTestId('expressive-action-container-outer-layer') - ).toHaveStyle({ width: 56 }); - } - ); -}); - -describe('AppbarV3 search', () => { - it('uses the placeholder as the searchbox label unless an explicit label is supplied', async () => { - const { rerender } = await render( - - ); - - expect( - screen.getByRole('searchbox', { name: 'Search messages' }) - ).toBeOnTheScreen(); - expect(screen.getByTestId('appbar-search-container')).toHaveStyle({ - backgroundColor: getTheme().colors.surfaceContainer, - }); - - await rerender( - - ); - - expect( - screen.getByRole('searchbox', { name: 'Message search' }) - ).toBeOnTheScreen(); - }); - - it('configures the search field, forwards its behavior, and constrains its width', async () => { - const onChangeText = jest.fn(); - const SearchAppbar = () => { - const [value, setValue] = React.useState(''); - - return ( - { - setValue(nextValue); - onChangeText(nextValue); - }, - testID: 'message-search', - }} - trailingActions={[ - { - key: 'more', - icon: 'dots-vertical', - 'aria-label': 'More options', - }, - ]} - /> - ); - }; - - await render(); - - const searchbox = screen.getByRole('searchbox', { - name: 'Search messages', - }); - expect(searchbox).toHaveStyle({ - color: getTheme().colors.onSurface, - textAlign: 'center', - }); - expect(searchbox).toHaveProp( - 'placeholderTextColor', - getTheme().colors.onSurfaceVariant - ); - expect(screen.getByTestId('message-search-container')).toHaveStyle({ - backgroundColor: getTheme().colors.surfaceContainerHighest, - }); - expect( - screen.getByRole('button', { name: 'Navigate back' }) - ).toBeOnTheScreen(); - expect( - screen.getByRole('button', { name: 'More options' }) - ).toBeOnTheScreen(); - - await userEvent.type(searchbox, 'draft'); - expect(onChangeText).toHaveBeenLastCalledWith('draft'); - expect(searchbox).toHaveProp('value', 'draft'); - - expect( - screen.getByTestId('message-search-container-outer-layer') - ).toHaveStyle({ width: '100%' }); - expect(screen.getByTestId('appbar-search-width-limiter')).toHaveStyle({ - width: '100%', - maxWidth: 720, - }); - }); -}); - -describe('AppbarV3 accessibility', () => { - it.each(writtenHeadlineVariants)( - 'exposes a written %s headline as a heading', - async (variant) => { - await render(); - - expect(screen.getByRole('heading', { name: 'Inbox' })).toBeOnTheScreen(); - } - ); - - it('hides a small headline image behind one named heading', async () => { - await render( - - ); - - expect(screen.getAllByRole('heading')).toHaveLength(1); - expect(screen.getByRole('heading', { name: 'Inbox' })).toBeOnTheScreen(); - expect(screen.queryByRole('img')).not.toBeOnTheScreen(); - expect(screen.queryByText('Brand words')).not.toBeOnTheScreen(); - }); - - it.each(['medium-flexible', 'large-flexible'] as const)( - 'does not expose duplicate content for a %s headline image', - async (variant) => { - await render( - - ); - - expect(screen.getAllByRole('heading', { name: 'Inbox' })).toHaveLength(1); - expect(screen.queryByRole('img')).not.toBeOnTheScreen(); - expect(screen.queryByLabelText('Brand artwork')).not.toBeOnTheScreen(); - } - ); - - it('exposes a pressable written headline as a named button and heading', async () => { - const onHeadlinePress = jest.fn(); - await render( - - ); - - expect(screen.getByRole('button', { name: 'Inbox' })).toBeOnTheScreen(); - expect(screen.getByRole('heading', { name: 'Inbox' })).toBeOnTheScreen(); - }); - - it('does not invoke a disabled headline action', async () => { - const onHeadlinePress = jest.fn(); - await render( - - ); - - const headlineButton = screen.getByRole('button', { - name: 'Inbox', - disabled: true, - }); - await userEvent.press(headlineButton); - - expect(onHeadlinePress).not.toHaveBeenCalled(); - }); - - it('names a pressable small headline image from its fallback headline', async () => { - await render( - {}} - /> - ); - - expect(screen.getByRole('button', { name: 'Inbox' })).toBeOnTheScreen(); - }); - - it('forwards custom headline button accessibility props', async () => { - const onAccessibilityAction = jest.fn(); - await render( - {}} - headlinePressableProps={{ - accessibilityActions: [{ name: 'activate', label: 'Open inbox' }], - accessibilityHint: 'Opens the inbox menu', - accessibilityLabel: 'Inbox options', - accessibilityState: { busy: true, expanded: true }, - accessibilityValue: { text: 'Unread messages available' }, - onAccessibilityAction, - }} - /> - ); - - const titleButton = screen.getByRole('button', { - name: 'Inbox options', - busy: true, - expanded: true, - }); - - expect(titleButton).toHaveProp( - 'accessibilityActions', - expect.arrayContaining([ - expect.objectContaining({ name: 'activate', label: 'Open inbox' }), - ]) - ); - expect(titleButton).toHaveProp('accessibilityHint', 'Opens the inbox menu'); - expect(titleButton).toHaveAccessibilityValue({ - text: 'Unread messages available', - }); - expect(titleButton).toHaveProp( - 'onAccessibilityAction', - onAccessibilityAction - ); - }); - - it('uses default and custom labels for back buttons', async () => { - await render( - - - - - ); - - expect(screen.getByRole('button', { name: 'Back' })).toBeOnTheScreen(); - expect( - screen.getByRole('button', { name: 'Return to inbox' }) - ).toBeOnTheScreen(); - }); - - it('preserves trailing action labels, hints, disabled state, and busy state', async () => { - await render( - - ); - - const trailingAction = screen.getByRole('button', { - name: 'Save message', - busy: true, - disabled: true, - }); - - expect(trailingAction).toHaveProp( - 'accessibilityHint', - 'Saves the current draft' - ); - expect(trailingAction).toBeDisabled(); - expect(trailingAction).toBeBusy(); - }); - - it.each(['small', 'medium-flexible'] as const)( - 'hides decorative descendants of a %s headline image', - async (variant) => { - await render( - variant === 'small' ? ( - - ) : ( - - ) - ); - - const imageContainer = screen.getByTestId( - 'appbar-content-headline-image', - { includeHiddenElements: true } - ); - - expect(imageContainer).toHaveProp('aria-hidden', true); - expect(imageContainer).toHaveProp( - 'importantForAccessibility', - 'no-hide-descendants' - ); - expect( - screen.queryByRole('heading', { name: 'Brand words' }) - ).not.toBeOnTheScreen(); - } - ); - - it('exposes the leading button, headline, and trailing actions in source order', async () => { - await render( - - ); - - expect(screen.getAllByRole(/button|heading/)).toEqual([ - screen.getByRole('button', { name: 'Navigate back' }), - screen.getByRole('heading', { name: 'Inbox' }), - screen.getByRole('button', { name: 'Search inbox' }), - screen.getByRole('button', { name: 'More options' }), - ]); - }); - - it('does not remount a surviving trailing action when its configuration changes', async () => { - const { rerender } = await render( - - ); - const survivingTrailingAction = screen.getByRole('button', { - name: 'Keep action', - }); - - await rerender( - - ); - - expect(screen.getByRole('button', { name: 'Keep action' })).toBe( - survivingTrailingAction - ); - }); -}); diff --git a/src/index.tsx b/src/index.tsx index a7b8e58f80..7a45fc0c3b 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -45,7 +45,6 @@ export { default as Snackbar } from './components/Snackbar'; export { default as Surface } from './components/Surface'; export { default as Switch } from './components/Switch/Switch'; export { default as Appbar } from './components/Appbar'; -export { default as AppbarV3 } from './components/AppbarV3'; export { default as TouchableRipple } from './components/TouchableRipple/TouchableRipple'; export { default as TextInput } from './components/TextInput'; export { default as ToggleButton } from './components/ToggleButton'; @@ -56,25 +55,20 @@ export { default as Text, customText } from './components/Typography/Text'; // Types export type { Props as ActivityIndicatorProps } from './components/ActivityIndicator'; -export type { Props as AppbarProps } from './components/Appbar/Appbar'; -export type { Props as AppbarActionProps } from './components/Appbar/AppbarAction'; -export type { Props as AppbarBackActionProps } from './components/Appbar/AppbarBackAction'; -export type { Props as AppbarContentProps } from './components/Appbar/AppbarContent'; -export type { Props as AppbarHeaderProps } from './components/Appbar/AppbarHeader'; export type { - Props as AppbarV3Props, - AppbarFilledTrailingAction as AppbarV3FilledTrailingAction, - AppbarHeadlineAlignment as AppbarV3HeadlineAlignment, - AppbarHeadlinePressableProps as AppbarV3HeadlinePressableProps, - AppbarHeadlineTextProps as AppbarV3HeadlineTextProps, - AppbarLeadingButton as AppbarV3LeadingButton, - AppbarSearchbarProps as AppbarV3SearchbarProps, - AppbarStandardTrailingAction as AppbarV3StandardTrailingAction, - AppbarTextProps as AppbarV3TextProps, - AppbarTrailingAction as AppbarV3TrailingAction, - AppbarTrailingActions as AppbarV3TrailingActions, - AppbarVariant as AppbarV3Variant, -} from './components/AppbarV3'; + Props as AppbarProps, + AppbarFilledTrailingAction, + AppbarHeadlineAlignment, + AppbarHeadlinePressableProps, + AppbarHeadlineTextProps, + AppbarLeadingButton, + AppbarSearchbarProps, + AppbarStandardTrailingAction, + AppbarTextProps, + AppbarTrailingAction, + AppbarTrailingActions, + AppbarVariant, +} from './components/Appbar'; export type { Props as AvatarIconProps } from './components/Avatar/AvatarIcon'; export type { Props as AvatarImageProps } from './components/Avatar/AvatarImage'; export type { Props as AvatarTextProps } from './components/Avatar/AvatarText';