diff --git a/src/CONST/SENTRY_LABEL.ts b/src/CONST/SENTRY_LABEL.ts index 398101f1397a..c5ad22805d41 100644 --- a/src/CONST/SENTRY_LABEL.ts +++ b/src/CONST/SENTRY_LABEL.ts @@ -195,6 +195,7 @@ const SENTRY_LABEL = { WORKSPACES: 'NavigationTabBar-Workspaces', ACCOUNT: 'NavigationTabBar-Account', HOME: 'NavigationTabBar-Home', + COLLAPSE: 'NavigationTabBar-Collapse', FLOATING_ACTION_BUTTON: 'NavigationTabBar-FloatingActionButton', FLOATING_RECEIPT_BUTTON: 'NavigationTabBar-FloatingReceiptButton', FLOATING_GPS_BUTTON: 'NavigationTabBar-FloatingGpsButton', diff --git a/src/components/Navigation/FlatNavigationBar/FlatNavAccountStatus.tsx b/src/components/Navigation/FlatNavigationBar/FlatNavAccountStatus.tsx index 09d5a938203a..5c94808afaf5 100644 --- a/src/components/Navigation/FlatNavigationBar/FlatNavAccountStatus.tsx +++ b/src/components/Navigation/FlatNavigationBar/FlatNavAccountStatus.tsx @@ -1,4 +1,5 @@ import Hoverable from '@components/Hoverable'; +import {getCollapseFadeStyle} from '@components/Navigation/SearchSidebarCollapseStore'; import Text from '@components/Text'; import Tooltip from '@components/Tooltip'; @@ -16,13 +17,18 @@ import CONST from '@src/CONST'; import React from 'react'; import {View} from 'react-native'; +import Animated from 'react-native-reanimated'; + +type FlatNavAccountStatusProps = { + isCollapsed?: boolean; +}; /** * The signed-in user's emoji status on the right of the flat navigation bar's Account row, with the status text in a * tooltip. In the expanded bar the status sits here instead of as a badge on the avatar, which would crowd the avatar's * ring and indicator dot. */ -function FlatNavAccountStatus() { +function FlatNavAccountStatus({isCollapsed = false}: FlatNavAccountStatusProps) { const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); const {translate, dateFnsLocale} = useLocalize(); @@ -33,35 +39,39 @@ function FlatNavAccountStatus() { return null; } + const collapseFadeStyle = getCollapseFadeStyle(isCollapsed); + const timezone = currentUserPersonalDetails.timezone?.selected ?? CONST.DEFAULT_TIME_ZONE.selected; const formattedClearAfterDate = DateUtils.getStatusUntilDate(translate, dateFnsLocale, currentUserPersonalDetails.status?.clearAfter ?? '', timezone, timezone); const tooltipText = getStatusTooltipText(currentUserPersonalDetails.status?.text ?? '', formattedClearAfterDate); return ( - - {/* Tooltip shows on mouse handlers it injects into its child, which Hoverable does not forward, so its target is a plain View */} - - - {(isHovered) => ( - - {emojiCode} - - )} - - - + + + {/* Tooltip shows on mouse handlers it injects into its child, which Hoverable does not forward, so its target is a plain View */} + + + {(isHovered) => ( + + {emojiCode} + + )} + + + + ); } diff --git a/src/components/Navigation/FlatNavigationBar/FlatNavCollapseToggle.tsx b/src/components/Navigation/FlatNavigationBar/FlatNavCollapseToggle.tsx new file mode 100644 index 000000000000..725dd15eabe8 --- /dev/null +++ b/src/components/Navigation/FlatNavigationBar/FlatNavCollapseToggle.tsx @@ -0,0 +1,57 @@ +/** The flat navigation bar's toggle for collapsing it into an icon rail and expanding it back. */ +import SidebarLeftIcon from '@assets/images/sidebar-left.svg'; +import SidebarRightIcon from '@assets/images/sidebar-right.svg'; + +import Icon from '@components/Icon'; +import {PressableWithFeedback} from '@components/Pressable'; +import Tooltip from '@components/Tooltip'; + +import useLocalize from '@hooks/useLocalize'; +import useStyleUtils from '@hooks/useStyleUtils'; +import useTheme from '@hooks/useTheme'; +import useThemeStyles from '@hooks/useThemeStyles'; + +import variables from '@styles/variables'; + +import CONST from '@src/CONST'; + +import React from 'react'; + +type FlatNavCollapseToggleProps = { + isCollapsed: boolean; + + onPress: () => void; +}; + +function FlatNavCollapseToggle({isCollapsed, onPress}: FlatNavCollapseToggleProps) { + const styles = useThemeStyles(); + const StyleUtils = useStyleUtils(); + const theme = useTheme(); + const {translate} = useLocalize(); + + const label = translate(isCollapsed ? 'reportActionCompose.expand' : 'reportActionCompose.collapse'); + + return ( + + + + + + ); +} + +export default FlatNavCollapseToggle; diff --git a/src/components/Navigation/FlatNavigationBar/FlatNavCreateButton.tsx b/src/components/Navigation/FlatNavigationBar/FlatNavCreateButton.tsx index e8e88170400d..5a5a6a319261 100644 --- a/src/components/Navigation/FlatNavigationBar/FlatNavCreateButton.tsx +++ b/src/components/Navigation/FlatNavigationBar/FlatNavCreateButton.tsx @@ -7,7 +7,6 @@ import usePopoverPosition from '@hooks/usePopoverPosition'; import useThemeStyles from '@hooks/useThemeStyles'; import CreateMenuPopover from '@pages/inbox/sidebar/FABPopoverContent/CreateMenuPopover'; -import useCreateMenuVisibility from '@pages/inbox/sidebar/FABPopoverContent/useCreateMenuVisibility'; import CONST from '@src/CONST'; import type {AnchorPosition} from '@src/styles'; @@ -16,20 +15,36 @@ import type AnchorAlignment from '@src/types/utils/AnchorAlignment'; import type {ComponentRef} from 'react'; import type {View} from 'react-native'; -import React, {useRef, useState} from 'react'; +import {useRef, useState} from 'react'; const CREATE_MENU_ANCHOR_ALIGNMENT: AnchorAlignment = { horizontal: CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.LEFT, vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.TOP, }; +type FlatNavCreateButtonProps = { + /** Shrinks the button to a round icon-only "+", for the collapsed bar */ + isCompact?: boolean; + + isCreateMenuActive: boolean; + + isCreateMenuVisible: boolean; + + showCreateMenu: () => void; + + hideCreateMenu: () => void; + + /** Called once the create menu has fully closed and its modal is gone from the screen */ + onCreateMenuHidden?: () => void; +}; + /** Opens the same create menu as the floating action button. */ -function FlatNavCreateButton() { +function FlatNavCreateButton({isCompact = false, isCreateMenuActive, isCreateMenuVisible, showCreateMenu, hideCreateMenu, onCreateMenuHidden}: FlatNavCreateButtonProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); const icons = useMemoizedLazyExpensifyIcons(['Plus']); const {calculatePopoverPosition} = usePopoverPosition(); - const {isCreateMenuActive, isCreateMenuVisible, showCreateMenu, hideCreateMenu} = useCreateMenuVisibility(); + const buttonRef = useRef>(null); const isOpeningRef = useRef(false); const [anchorPosition, setAnchorPosition] = useState(); @@ -60,6 +75,7 @@ function FlatNavCreateButton() { anchorRef={buttonRef} anchorPosition={anchorPosition} anchorAlignment={CREATE_MENU_ANCHOR_ALIGNMENT} + onModalHide={onCreateMenuHidden} /> ); diff --git a/src/components/Navigation/FlatNavigationBar/FlatNavItem.tsx b/src/components/Navigation/FlatNavigationBar/FlatNavItem.tsx index b9f930be6218..c4d38bf6bb05 100644 --- a/src/components/Navigation/FlatNavigationBar/FlatNavItem.tsx +++ b/src/components/Navigation/FlatNavigationBar/FlatNavItem.tsx @@ -1,5 +1,6 @@ import Icon from '@components/Icon'; import getTabIconFill from '@components/Navigation/NavigationTabBar/getTabIconFill'; +import {getCollapseFadeStyle} from '@components/Navigation/SearchSidebarCollapseStore'; import {PressableWithFeedback} from '@components/Pressable'; import Text from '@components/Text'; @@ -17,6 +18,7 @@ import type {ColorValue} from 'react-native'; import React from 'react'; import {View} from 'react-native'; +import Animated from 'react-native-reanimated'; type FlatNavItemProps = { /** Translated row label */ @@ -32,6 +34,9 @@ type FlatNavItemProps = { isSelected: boolean; + /** Whether the row keeps only its icon, so the bar can narrow to an icon rail */ + isCollapsed?: boolean; + /** Draws the row taller than the destination rows, as the Account row is */ isTall?: boolean; @@ -59,6 +64,7 @@ function FlatNavItem({ renderLeftElement, rightElement, isSelected, + isCollapsed = false, isTall = false, statusIndicatorColor, accessibilityLabel, @@ -78,6 +84,9 @@ function FlatNavItem({ return isHovered ? styles.highlightBG : undefined; }; + // The label stays mounted and fades, rather than disappearing the moment the bar starts narrowing. + const collapseFadeStyle = getCollapseFadeStyle(isCollapsed); + return ( )} {renderLeftElement?.({backgroundColor: rowBackgroundColor})} - - {label} - + + + {label} + + {rightElement} ); diff --git a/src/components/Navigation/FlatNavigationBar/FlatNavLogo.tsx b/src/components/Navigation/FlatNavigationBar/FlatNavLogo.tsx index 1f3a970bc612..ac47aa9238c3 100644 --- a/src/components/Navigation/FlatNavigationBar/FlatNavLogo.tsx +++ b/src/components/Navigation/FlatNavigationBar/FlatNavLogo.tsx @@ -13,10 +13,13 @@ import React from 'react'; type FlatNavLogoProps = { onPress: () => void; + + /** Whether the navigation bar is visually collapsed, so the logo fades out and stops accepting interaction. */ + isCollapsed?: boolean; }; /** Expensify wordmark at the top of the flat navigation bar, which leads Home like the logo in the icon bar. */ -function FlatNavLogo({onPress}: FlatNavLogoProps) { +function FlatNavLogo({onPress, isCollapsed = false}: FlatNavLogoProps) { const theme = useTheme(); const {translate} = useLocalize(); const icons = useMemoizedLazyExpensifyIcons(['ExpensifyWordmark']); @@ -28,6 +31,9 @@ function FlatNavLogo({onPress}: FlatNavLogoProps) { testID="ExpensifyLogoButton" onPress={onPress} sentryLabel={CONST.SENTRY_LABEL.NAVIGATION_TAB_BAR.EXPENSIFY_LOGO} + aria-hidden={isCollapsed} + tabIndex={isCollapsed ? -1 : 0} + disabled={isCollapsed} > () => setIsSearchTabHovered(false), []); + // A peek has no hover out to end it when the bar goes away while hovered, on a switch to the narrow layout or an unmount. + useEffect(() => endPeek, [endPeek]); + + const {isCreateMenuActive, isCreateMenuVisible, showCreateMenu, hideCreateMenu} = useCreateMenuVisibility(); + const barContainerRef = useRef(null); + + // Only keyboard focus counts: an item clicked with the mouse keeps focus too, and must not hold the bar open after the pointer leaves. + const hasKeyboardFocusInside = () => { + const element = barContainerRef.current; + return isHTMLElement(element) && !!element.querySelector(':focus-visible'); + }; + + // Closing the Create menu hands focus back to its button, and that focus must not reopen a peek the pointer has already left. + const startPeekOnKeyboardFocus = () => { + if (!hasKeyboardFocusInside()) { + return; + } + startPeek(); + }; + + // The menu's overlay covers the bar until its modal is gone, so the bar never reads as hovered before then. + // Checking any earlier ends the peek under a pointer that is still on the bar, and the bar then peeks right back. + const endPeekIfPointerAndFocusLeft = () => { + const element = barContainerRef.current; + const isHovered = isHTMLElement(element) && element.matches(':hover'); + if (isCreateMenuVisible || isHovered || hasKeyboardFocusInside()) { + return; + } + endPeek(); + }; + + const endPeekIfIdle = () => { + if (isCreateMenuVisible || hasKeyboardFocusInside()) { + return; + } + endPeek(); + }; + + const endPeekUnlessStaying = (event: NativeSyntheticEvent) => { + if (isCreateMenuVisible) { + return; + } + const currentTarget = event.currentTarget; + // On web the native event is a DOM FocusEvent, whose relatedTarget is the element receiving focus. + const relatedTarget = 'relatedTarget' in event.nativeEvent ? event.nativeEvent.relatedTarget : null; + // Tabbing between items inside the bar keeps the peek open. + if (isHTMLElement(currentTarget) && isHTMLElement(relatedTarget) && currentTarget.contains(relatedTarget)) { + return; + } + const element = barContainerRef.current; + if (isHTMLElement(element) && element.matches(':hover')) { + return; + } + endPeek(); + }; + const accountLabel = currentUserPersonalDetails.displayName ? currentUserPersonalDetails.displayName : translate('initialSettingsPage.account'); return ( <> {!!isDebugModeEnabled && } - - {(isBarHovered) => ( - - - - - - - - - + + {(isBarHovered) => ( + - - - - setIsSearchTabHovered(true)} - onHoverOut={() => setIsSearchTabHovered(false)} - /> - - - - - - - - - - ( - + + - )} - rightElement={} - isSelected={isAccountSelected} - isTall - accessibilityLabel={getTabAccessibilityLabel(`${accountLabel}, ${translate('sidebarScreen.buttonMySettings')}`, !!accountStatus, translate)} - sentryLabel={CONST.SENTRY_LABEL.NAVIGATION_TAB_BAR.ACCOUNT} - onPress={navigateToAccount} - /> - - - )} - + + + + + {/* The header stays out of the peek, so pressing the toggle never races the bar widening under the pointer. */} + + + + + + + + + + + setIsSearchTabHovered(true)} + onHoverOut={() => setIsSearchTabHovered(false)} + /> + + + + + + + + + + + ( + + + + )} + rightElement={} + isSelected={isAccountSelected} + isTall + accessibilityLabel={getTabAccessibilityLabel(`${accountLabel}, ${translate('sidebarScreen.buttonMySettings')}`, !!accountStatus, translate)} + sentryLabel={CONST.SENTRY_LABEL.NAVIGATION_TAB_BAR.ACCOUNT} + onPress={navigateToAccount} + /> + + + + + )} + + ); } diff --git a/src/components/Navigation/FlatNavigationBar/useNavigationBarWidth.ts b/src/components/Navigation/FlatNavigationBar/useNavigationBarWidth.ts index c9334f96a821..edeee153c94e 100644 --- a/src/components/Navigation/FlatNavigationBar/useNavigationBarWidth.ts +++ b/src/components/Navigation/FlatNavigationBar/useNavigationBarWidth.ts @@ -1,16 +1,26 @@ +import {getFlatNavigationBarLayoutWidth} from '@components/Navigation/SearchSidebarCollapseStore'; + +import useOnyx from '@hooks/useOnyx'; + import variables from '@styles/variables'; +import ONYXKEYS from '@src/ONYXKEYS'; + import useShouldUseFlatNavigationBar from './useShouldUseFlatNavigationBar'; -/** Width of the wide layout's left navigation bar for the given bar variant. */ -function getNavigationBarWidth(shouldUseFlatNavigationBar: boolean) { - return shouldUseFlatNavigationBar ? variables.flatNavigationBarWidth : variables.navigationTabBarSize; +/** Width of the wide layout's left navigation bar for the given bar variant. Peeking overlays the content, so only the collapsed flag counts. */ +function getNavigationBarWidth(shouldUseFlatNavigationBar: boolean, isCollapsed = false) { + return shouldUseFlatNavigationBar ? getFlatNavigationBarLayoutWidth(isCollapsed) : variables.navigationTabBarSize; } /** Width of the wide layout's left navigation bar, which everything placed next to it is offset by. */ function useNavigationBarWidth() { - return getNavigationBarWidth(useShouldUseFlatNavigationBar()); + const shouldUseFlatNavigationBar = useShouldUseFlatNavigationBar(); + const [isCollapsed = false] = useOnyx(ONYXKEYS.NVP_SEARCH_SIDEBAR, { + selector: (nvp) => nvp?.isCollapsed ?? false, + }); + + return getNavigationBarWidth(shouldUseFlatNavigationBar, isCollapsed); } export default useNavigationBarWidth; -export {getNavigationBarWidth}; diff --git a/src/components/Navigation/SearchSidebar.tsx b/src/components/Navigation/SearchSidebar.tsx index c0d7d37e9242..45e4c4eca82a 100644 --- a/src/components/Navigation/SearchSidebar.tsx +++ b/src/components/Navigation/SearchSidebar.tsx @@ -29,6 +29,7 @@ import React, {useEffect} from 'react'; import {View} from 'react-native'; import Animated from 'react-native-reanimated'; +import useShouldUseFlatNavigationBar from './FlatNavigationBar/useShouldUseFlatNavigationBar'; import { useSearchSidebarCollapse, useSearchSidebarCollapseFadeStyle, @@ -49,6 +50,7 @@ function SearchSidebar({state}: SearchSidebarProps) { const {isOffline} = useNetwork(); const shouldShowLoadingBarForReports = useLoadingBarVisibility(); const {shouldUseNarrowLayout} = useResponsiveLayout(); + const shouldUseFlatNavigationBar = useShouldUseFlatNavigationBar(); const {isCollapsed, toggleSidebar, startPeek, endPeek} = useSearchSidebarCollapse(); const layoutSpacerStyle = useSearchSidebarLayoutWidthStyle(); const visualSidebarWidthStyle = useSearchSidebarVisualWidthStyle(); @@ -117,7 +119,8 @@ function SearchSidebar({state}: SearchSidebarProps) { shouldDisplaySearch={false} shouldDisplayHelpButton={false} > - {toggleButton} + {/* The flat navigation bar has its own toggle for the one flag both share. */} + {!shouldUseFlatNavigationBar && toggleButton} diff --git a/src/components/Navigation/SearchSidebarCollapseStore.ts b/src/components/Navigation/SearchSidebarCollapseStore.ts index c33e6a9e1c83..d2ab8b60008c 100644 --- a/src/components/Navigation/SearchSidebarCollapseStore.ts +++ b/src/components/Navigation/SearchSidebarCollapseStore.ts @@ -7,6 +7,7 @@ import variables from '@styles/variables'; import ONYXKEYS from '@src/ONYXKEYS'; import type {ViewStyle} from 'react-native'; +import type {ValueOf} from 'type-fest'; import {useSyncExternalStore} from 'react'; import {Platform} from 'react-native'; @@ -15,12 +16,27 @@ const SEARCH_SIDEBAR_COLLAPSE_ANIMATION_DURATION_MS = 220; const SEARCH_SIDEBAR_COLLAPSE_TRANSLATE_X = -8; const TOGGLE_BUTTON_COLLAPSED_TRANSLATE_X = -10; +/** + * The surfaces that share the collapsed flag. They collapse together, but each one peeks on its own: hovering the + * flat navigation bar must not widen the Spend sidebar next to it, and the other way round. + */ +const COLLAPSE_SURFACE = { + NAVIGATION_BAR: 'navigationBar', + SEARCH_SIDEBAR: 'searchSidebar', +} as const; + +type CollapseSurface = ValueOf; + const layoutTransitionStyle: ViewStyle = Platform.OS === 'web' ? {transition: `width ${SEARCH_SIDEBAR_COLLAPSE_ANIMATION_DURATION_MS}ms ease, margin-left ${SEARCH_SIDEBAR_COLLAPSE_ANIMATION_DURATION_MS}ms ease`} : {}; const fadeTransitionStyle: ViewStyle = Platform.OS === 'web' ? {transition: `opacity ${SEARCH_SIDEBAR_COLLAPSE_ANIMATION_DURATION_MS}ms ease, transform ${SEARCH_SIDEBAR_COLLAPSE_ANIMATION_DURATION_MS}ms ease`} : {}; -let isPeeking = false; +// The account avatar's box is wider than a row's icon, so collapsed it would sit right of the icon column. +// Sliding it by half that difference lines it up, and a transform animates where a padding change would jump. +const ACCOUNT_AVATAR_COLLAPSED_TRANSLATE_X = -(variables.avatarSizeSmall - variables.iconSizeNormal) / 2; + +let peekingSurface: CollapseSurface | null = null; const listeners = new Set<() => void>(); @@ -37,52 +53,59 @@ function notify() { } } -function getPeekSnapshot() { - return isPeeking; -} - function getSearchSidebarWidth(progress: number) { return variables.searchSidebarExpandedWidth + (variables.searchSidebarCollapsedWidth - variables.searchSidebarExpandedWidth) * progress; } function setSearchSidebarCollapsed(collapsed: boolean) { - isPeeking = false; + peekingSurface = null; notify(); SearchSidebarActions.setCollapsed(collapsed); } -function startPeek(isCollapsed: boolean) { - if (!isCollapsed || isPeeking) { +function startPeek(surface: CollapseSurface, isCollapsed: boolean) { + if (!isCollapsed || peekingSurface !== null) { return; } - isPeeking = true; + peekingSurface = surface; notify(); } -function endPeek() { - if (!isPeeking) { +function endPeek(surface: CollapseSurface) { + if (peekingSurface !== surface) { return; } - isPeeking = false; + peekingSurface = null; notify(); } -function useSearchSidebarCollapse() { +const isSurfacePeekingSnapshots: Record boolean> = { + [COLLAPSE_SURFACE.NAVIGATION_BAR]: () => peekingSurface === COLLAPSE_SURFACE.NAVIGATION_BAR, + [COLLAPSE_SURFACE.SEARCH_SIDEBAR]: () => peekingSurface === COLLAPSE_SURFACE.SEARCH_SIDEBAR, +}; + +const endPeekBySurface: Record void> = { + [COLLAPSE_SURFACE.NAVIGATION_BAR]: () => endPeek(COLLAPSE_SURFACE.NAVIGATION_BAR), + [COLLAPSE_SURFACE.SEARCH_SIDEBAR]: () => endPeek(COLLAPSE_SURFACE.SEARCH_SIDEBAR), +}; + +function useSearchSidebarCollapse(surface: CollapseSurface = COLLAPSE_SURFACE.SEARCH_SIDEBAR) { const [searchSidebarNVP] = useOnyx(ONYXKEYS.NVP_SEARCH_SIDEBAR); const collapsed = searchSidebarNVP?.isCollapsed ?? false; - const peeking = useSyncExternalStore(subscribe, getPeekSnapshot, getPeekSnapshot); + const isSurfacePeekingSnapshot = isSurfacePeekingSnapshots[surface]; + const peeking = useSyncExternalStore(subscribe, isSurfacePeekingSnapshot, isSurfacePeekingSnapshot); const toggleSidebar = () => setSearchSidebarCollapsed(!collapsed); - const startSidebarPeek = () => startPeek(collapsed); + const startSurfacePeek = () => startPeek(surface, collapsed); return { isCollapsed: collapsed, isPeeking: peeking, isVisuallyCollapsed: collapsed && !peeking, toggleSidebar, - startPeek: startSidebarPeek, - endPeek, + startPeek: startSurfacePeek, + endPeek: endPeekBySurface[surface], }; } @@ -104,9 +127,8 @@ function useSearchSidebarContentOffsetStyle() { return {...layoutTransitionStyle, marginLeft: getSearchSidebarWidth(collapsed ? 1 : 0)}; } -function useSearchSidebarCollapseFadeStyle() { - const {isVisuallyCollapsed} = useSearchSidebarCollapse(); - +/** Fades a label out and nudges it toward the icon column while its surface is visually collapsed. */ +function getCollapseFadeStyle(isVisuallyCollapsed: boolean): ViewStyle { return { ...fadeTransitionStyle, opacity: isVisuallyCollapsed ? 0 : 1, @@ -114,6 +136,12 @@ function useSearchSidebarCollapseFadeStyle() { }; } +function useSearchSidebarCollapseFadeStyle() { + const {isVisuallyCollapsed} = useSearchSidebarCollapse(); + + return getCollapseFadeStyle(isVisuallyCollapsed); +} + function useSearchSidebarToggleButtonStyle() { const {isVisuallyCollapsed} = useSearchSidebarCollapse(); @@ -123,8 +151,43 @@ function useSearchSidebarToggleButtonStyle() { }; } +/** + * Layout space the flat navigation bar reserves. Peeking overlays the content rather than pushing it, so this + * ignores the peek. + */ +function getFlatNavigationBarLayoutWidth(isCollapsed: boolean): number { + return isCollapsed ? variables.flatNavigationBarCollapsedWidth : variables.flatNavigationBarWidth; +} + +/** The layout box the flat navigation bar reserves, which eases with the bar so the content beside it follows. */ +function getFlatNavigationBarLayoutWidthStyle(isCollapsed: boolean): ViewStyle { + return {...layoutTransitionStyle, width: getFlatNavigationBarLayoutWidth(isCollapsed)}; +} + +/** What the flat navigation bar draws, which widens back out while the pointer peeks at it. */ +function getFlatNavigationBarVisualWidthStyle(isVisuallyCollapsed: boolean): ViewStyle { + return {...layoutTransitionStyle, width: getFlatNavigationBarLayoutWidth(isVisuallyCollapsed)}; +} + +/** The shadow only reads while a collapsed bar peeks over the content. Expanded, the bar has nothing to sit above. */ +function getFlatNavigationBarPeekShadowStyle(isPeeking: boolean): ViewStyle { + return {...fadeTransitionStyle, opacity: isPeeking ? 1 : 0}; +} + +function getFlatNavigationBarAccountAvatarStyle(isVisuallyCollapsed: boolean): ViewStyle { + return {...fadeTransitionStyle, transform: [{translateX: isVisuallyCollapsed ? ACCOUNT_AVATAR_COLLAPSED_TRANSLATE_X : 0}]}; +} + export { + COLLAPSE_SURFACE, SEARCH_SIDEBAR_COLLAPSE_ANIMATION_DURATION_MS, + layoutTransitionStyle, + getCollapseFadeStyle, + getFlatNavigationBarAccountAvatarStyle, + getFlatNavigationBarLayoutWidth, + getFlatNavigationBarLayoutWidthStyle, + getFlatNavigationBarPeekShadowStyle, + getFlatNavigationBarVisualWidthStyle, useSearchSidebarCollapse, useSearchSidebarLayoutWidthStyle, useSearchSidebarVisualWidthStyle, diff --git a/src/libs/Navigation/AppNavigator/Navigators/TabNavigatorBar.tsx b/src/libs/Navigation/AppNavigator/Navigators/TabNavigatorBar.tsx index d34a70869dd9..761d1ff88020 100644 --- a/src/libs/Navigation/AppNavigator/Navigators/TabNavigatorBar.tsx +++ b/src/libs/Navigation/AppNavigator/Navigators/TabNavigatorBar.tsx @@ -1,10 +1,11 @@ import {useFullScreenBlockingViewState} from '@components/FullScreenBlockingViewContextProvider'; import FlatNavigationBar from '@components/Navigation/FlatNavigationBar'; -import {getNavigationBarWidth} from '@components/Navigation/FlatNavigationBar/useNavigationBarWidth'; +import useNavigationBarWidth from '@components/Navigation/FlatNavigationBar/useNavigationBarWidth'; import useShouldUseFlatNavigationBar from '@components/Navigation/FlatNavigationBar/useShouldUseFlatNavigationBar'; import NavigationTabBar from '@components/Navigation/NavigationTabBar'; import NAVIGATION_TABS from '@components/Navigation/NavigationTabBar/NAVIGATION_TABS'; import ROUTE_TO_NAVIGATION_TAB from '@components/Navigation/NavigationTabBar/ROUTE_TO_NAVIGATION_TAB'; +import {COLLAPSE_SURFACE, layoutTransitionStyle, useSearchSidebarCollapse} from '@components/Navigation/SearchSidebarCollapseStore'; import {SetNavigatorTabBarVisibleContext} from '@components/Navigation/TabBarBottomContent/NavigatorTabBarVisibilityProvider'; import usePrevious from '@hooks/usePrevious'; @@ -37,7 +38,8 @@ function TabNavigatorBar({state}: Pick) { const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); const shouldUseFlatNavigationBar = useShouldUseFlatNavigationBar(); - const navigationBarWidth = getNavigationBarWidth(shouldUseFlatNavigationBar); + const navigationBarWidth = useNavigationBarWidth(); + const {isPeeking: isNavigationBarPeeking} = useSearchSidebarCollapse(COLLAPSE_SURFACE.NAVIGATION_BAR); const activeRoute = state.routes[state.index]; const selectedTab = ROUTE_TO_NAVIGATION_TAB[activeRoute?.name ?? SCREENS.HOME] ?? NAVIGATION_TABS.HOME; const isAtRoot = isTabRouteAtRoot(activeRoute); @@ -96,9 +98,16 @@ function TabNavigatorBar({state}: Pick) { // When the screen is not blocking the view, we need to raise the tab bar above the screen content so the DebugTabView is visible. // The container also spans the sidebar next to the bar, so floating content such as the debug view is not clipped. // tabNavigatorBarContainer's negative margin gives that width back, leaving only the bar's width as layout space. + // The width is what holds the central pane off the left edge, so it eases with the bar instead of snapping to the new width. + // A peeking bar is raised even over a blocking view, since it is drawn over the content. return ( {shouldUseFlatNavigationBar ? : } diff --git a/src/pages/inbox/sidebar/FABPopoverContent/CreateMenuPopover.tsx b/src/pages/inbox/sidebar/FABPopoverContent/CreateMenuPopover.tsx index 2c14ee2caf5a..5a80638d5ab8 100644 --- a/src/pages/inbox/sidebar/FABPopoverContent/CreateMenuPopover.tsx +++ b/src/pages/inbox/sidebar/FABPopoverContent/CreateMenuPopover.tsx @@ -33,10 +33,13 @@ type CreateMenuPopoverProps = { /** How the menu lines up with `anchorPosition` */ anchorAlignment?: AnchorAlignment; + + /** Called once the menu has fully closed and its modal is gone from the screen */ + onModalHide?: () => void; }; /** The create menu with every item, for any button that opens it. */ -function CreateMenuPopover({isVisible, onClose, anchorRef, anchorPosition, anchorAlignment}: CreateMenuPopoverProps) { +function CreateMenuPopover({isVisible, onClose, anchorRef, anchorPosition, anchorAlignment, onModalHide}: CreateMenuPopoverProps) { const [reportID] = useState(() => generateReportID()); return ( @@ -47,6 +50,7 @@ function CreateMenuPopover({isVisible, onClose, anchorRef, anchorPosition, ancho anchorRef={anchorRef} anchorPosition={anchorPosition} anchorAlignment={anchorAlignment} + onModalHide={onModalHide} animationInTiming={CONST.MODAL.ANIMATION_TIMING.FAB_IN} animationOutTiming={CONST.MODAL.ANIMATION_TIMING.FAB_OUT} > diff --git a/src/pages/inbox/sidebar/FABPopoverContent/FABPopoverMenu.tsx b/src/pages/inbox/sidebar/FABPopoverContent/FABPopoverMenu.tsx index 79f324b5589e..116c46c96e38 100644 --- a/src/pages/inbox/sidebar/FABPopoverContent/FABPopoverMenu.tsx +++ b/src/pages/inbox/sidebar/FABPopoverContent/FABPopoverMenu.tsx @@ -47,6 +47,9 @@ type FABPopoverMenuProps = { /** How the menu lines up with its anchor position */ anchorAlignment?: AnchorAlignment; + /** Called once the menu has fully closed and its modal is gone from the screen */ + onModalHide?: () => void; + children: React.ReactNode; }; @@ -64,6 +67,7 @@ function FABPopoverMenu({ animationOutTiming, anchorPosition: anchorPositionOverride, anchorAlignment = DEFAULT_ANCHOR_ALIGNMENT, + onModalHide, children, }: FABPopoverMenuProps) { const styles = useThemeStyles(); @@ -148,7 +152,10 @@ function FABPopoverMenu({ onClose={handleClose} isVisible={isVisible} onModalWillShow={() => setContentActivityMode('visible')} - onModalHide={() => setContentActivityMode('hidden')} + onModalHide={() => { + setContentActivityMode('hidden'); + onModalHide?.(); + }} fromSidebarMediumScreen={!shouldUseNarrowLayout} animationIn="fadeIn" animationOut="fadeOut" diff --git a/src/styles/index.ts b/src/styles/index.ts index 329504076e44..ed426cb60245 100644 --- a/src/styles/index.ts +++ b/src/styles/index.ts @@ -885,11 +885,30 @@ const staticStyles = (theme: ThemeColors) => backgroundColor: theme.appBG, }, + // Drawn as its own layer so the shadow can fade on its own, and only while a collapsed bar peeks over the content. + flatNavigationBarPeekShadow: { + ...StyleSheet.absoluteFill, + boxShadow: theme.shadow, + }, + flatNavigationBarHeader: { flexDirection: 'row', alignItems: 'center', + justifyContent: 'flex-end', height: variables.flatNavigationBarHeaderHeight, paddingLeft: variables.flatNavigationBarRowInset + variables.flatNavigationBarRowPadding, + paddingRight: variables.flatNavigationBarHeaderPaddingRight, + // The logo fades out in place while the toggle stays, so the header has to clip the logo as the bar narrows. + overflow: 'hidden', + }, + + // Lets the wordmark fade out in place while the toggle is the only thing left in the header. + flatNavigationBarLogoContainer: { + position: 'absolute', + left: variables.flatNavigationBarRowInset + variables.flatNavigationBarRowPadding, + top: 0, + bottom: 0, + justifyContent: 'center', }, // The "y" at the end of the wordmark already leaves empty space on its right, so the badge sits closer than the default badge margin @@ -907,6 +926,11 @@ const staticStyles = (theme: ThemeColors) => minHeight: variables.flatNavigationBarCreateButtonHeight, }, + // Collapsed, the button narrows with its container: rail width minus both insets equals its height, so the pill ends as a circle. + flatNavigationBarCreateButtonCompact: { + paddingHorizontal: 0, + }, + flatNavigationBarItem: { flexDirection: 'row', alignItems: 'center', @@ -915,6 +939,8 @@ const staticStyles = (theme: ThemeColors) => paddingHorizontal: variables.flatNavigationBarRowPadding, marginHorizontal: variables.flatNavigationBarRowInset, borderRadius: variables.componentBorderRadiusNormal, + // Labels stay mounted while they fade, so a collapsed row has to clip what no longer fits. + overflow: 'hidden', }, flatNavigationBarAccountItem: { diff --git a/src/styles/variables.ts b/src/styles/variables.ts index 462161bf0b75..440aceca9470 100644 --- a/src/styles/variables.ts +++ b/src/styles/variables.ts @@ -202,6 +202,10 @@ export default { searchSidebarCollapsedWidth: 76, navigationTabBarSize: 72, flatNavigationBarWidth: 232, + // Collapsed, a row shows only its icon: the row's inset (8) and padding (12) on each side around the 20px icon. + flatNavigationBarCollapsedWidth: 60, + // Expanded, the collapse toggle sits this far from the bar's right edge. Collapsed, the bar narrows until the toggle lands on the icon column. + flatNavigationBarHeaderPaddingRight: 20, flatNavigationBarItemHeight: 40, flatNavigationBarAccountItemHeight: 56, // Horizontal inset every row's background sits at, inside the bar's own width. diff --git a/tests/ui/FlatNavCreateButtonTest.tsx b/tests/ui/FlatNavCreateButtonTest.tsx index fb64acf8d733..37e8220d618f 100644 --- a/tests/ui/FlatNavCreateButtonTest.tsx +++ b/tests/ui/FlatNavCreateButtonTest.tsx @@ -5,6 +5,8 @@ import {LocaleContextProvider} from '@components/LocaleContextProvider'; import FlatNavCreateButton from '@components/Navigation/FlatNavigationBar/FlatNavCreateButton'; import OnyxListItemProvider from '@components/OnyxListItemProvider'; +import useCreateMenuVisibility from '@pages/inbox/sidebar/FABPopoverContent/useCreateMenuVisibility'; + import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {AnchorPosition} from '@src/styles'; @@ -53,10 +55,23 @@ jest.mock('@react-navigation/native', () => ({ useFocusEffect: jest.fn(), })); -function renderButton() { +function Harness({isCompact = false}: {isCompact?: boolean}) { + const menu = useCreateMenuVisibility(); + return ( + + ); +} + +function renderButton(isCompact = false) { render( - + , ); } @@ -144,4 +159,64 @@ describe('FlatNavCreateButton', () => { expect(mockCalculatePopoverPosition).toHaveBeenCalledTimes(1); expect(screen.getByTestId('CreateMenuPopover')).toBeOnTheScreen(); }); + + it('shrinks to an icon-only button when compact', async () => { + // Given the Create button in a collapsed bar + + // When the button renders + renderButton(true); + await waitForBatchedUpdatesWithAct(); + + // Then the "Create" text is gone, but the button keeps its name for screen readers + expect(screen.queryByText('Create')).not.toBeOnTheScreen(); + expect(screen.getByRole(CONST.ROLE.BUTTON, {name: 'Create'})).toBeOnTheScreen(); + }); + + it('still opens the menu when compact', async () => { + // Given the compact Create button in a collapsed bar + renderButton(true); + await waitForBatchedUpdatesWithAct(); + + // When it is pressed + pressCreate(); + await waitForBatchedUpdatesWithAct(); + + // Then it opens the same menu, so collapsing the bar loses no action + expect(screen.getByTestId('CreateMenuPopover')).toBeOnTheScreen(); + }); + + it('shows the "Create" text when not compact', async () => { + // Given the Create button in the expanded bar + + // When the button renders + renderButton(); + await waitForBatchedUpdatesWithAct(); + + // Then the text is drawn next to the icon + expect(screen.getByText('Create')).toBeOnTheScreen(); + }); + + it('calls showCreateMenu when the button is pressed while inactive', async () => { + // Given show and hide handlers + const showCreateMenu = jest.fn(); + const hideCreateMenu = jest.fn(); + render( + + + , + ); + await waitForBatchedUpdatesWithAct(); + + // When the button is pressed + pressCreate(); + await waitForBatchedUpdatesWithAct(); + + // Then the external show handler is called + expect(showCreateMenu).toHaveBeenCalledTimes(1); + }); }); diff --git a/tests/ui/FlatNavigationBarTest.tsx b/tests/ui/FlatNavigationBarTest.tsx index d70a9f04a01e..be5a944228dc 100644 --- a/tests/ui/FlatNavigationBarTest.tsx +++ b/tests/ui/FlatNavigationBarTest.tsx @@ -1,4 +1,4 @@ -import {cleanup, fireEvent, render, screen, within} from '@testing-library/react-native'; +import {act, cleanup, fireEvent, render, screen, within} from '@testing-library/react-native'; import ComposeProviders from '@components/ComposeProviders'; import {CurrentUserPersonalDetailsProvider} from '@components/CurrentUserPersonalDetailsProvider'; @@ -11,13 +11,17 @@ import {signOutAndRedirectToSignIn} from '@libs/actions/Session'; import {getIsSearchTabHovered, setIsSearchTabHovered} from '@libs/Navigation/helpers/searchTabPreloadStore'; import Navigation from '@libs/Navigation/Navigation'; +import variables from '@styles/variables'; + import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; +import type {StyleProp, ViewStyle} from 'react-native'; import type {ValueOf} from 'type-fest'; import React from 'react'; +import {StyleSheet} from 'react-native'; import Onyx from 'react-native-onyx'; import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; @@ -40,13 +44,62 @@ jest.mock('@components/Navigation/NavigationTabBar/useInsightsTabNavigation', () jest.mock('@hooks/useRestoreWorkspacesTabOnNavigate', () => () => mockNavigateToWorkspaces); jest.mock('@hooks/useInboxTabIndicatorStatus', () => () => mockInboxIndicator); jest.mock('@hooks/useWorkspacesTabIndicatorStatus', () => () => mockWorkspacesIndicator); -jest.mock('@components/Navigation/FlatNavigationBar/FlatNavCreateButton', () => () => null); +jest.mock('@react-navigation/native', () => ({ + ...jest.requireActual>('@react-navigation/native'), + useIsFocused: () => true, + useFocusEffect: jest.fn(), +})); +type MockCreateButtonProps = { + isCompact?: boolean; + isCreateMenuActive?: boolean; + isCreateMenuVisible?: boolean; + showCreateMenu?: () => void; + hideCreateMenu?: () => void; + onCreateMenuHidden?: () => void; +}; +let mockCreateButtonProps: MockCreateButtonProps | undefined; +jest.mock('@components/Navigation/FlatNavigationBar/FlatNavCreateButton', () => (props: MockCreateButtonProps) => { + mockCreateButtonProps = props; + return null; +}); +let mockIsElementHovered = false; +let mockIsFocusMovingInside = false; +let mockHasKeyboardFocusInside = false; +jest.mock('@libs/isHTMLElement', () => ({ + __esModule: true, + default: (val: unknown): val is HTMLElement => { + if ((!mockIsElementHovered && !mockIsFocusMovingInside && !mockHasKeyboardFocusInside) || typeof val !== 'object' || val === null) { + return false; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- attach DOM methods to the test instance for mock hover and focus verification + const target = val as {matches?: (selector: string) => boolean; contains?: (other: unknown) => boolean; querySelector?: (selector: string) => unknown}; + target.matches = (selector: string) => mockIsElementHovered && selector === ':hover'; + target.contains = () => mockIsFocusMovingInside; + target.querySelector = (selector: string) => (mockHasKeyboardFocusInside && selector === ':focus-visible' ? {} : null); + return true; + }, +})); jest.mock('@pages/inbox/sidebar/SupportalSwitcherButton', () => () => null); jest.mock('@components/Avatar/AccountNavigationAvatar', () => () => null); jest.mock('@libs/Navigation/Navigation', () => ({ __esModule: true, default: {navigate: jest.fn()}, })); +let mockOuterHoverOut: (() => void) | undefined; +let mockInnerHoverIn: (() => void) | undefined; +jest.mock( + '@components/Hoverable', + () => + ({children, onHoverIn, onHoverOut}: {children: React.ReactNode | ((isHovered: boolean) => React.ReactNode); onHoverIn?: () => void; onHoverOut?: () => void}) => { + if (onHoverOut) { + mockOuterHoverOut = onHoverOut; + } + if (onHoverIn) { + mockInnerHoverIn = onHoverIn; + } + return typeof children === 'function' ? children(false) : children; + }, +); jest.mock('@libs/actions/Session', () => ({ ...jest.requireActual>('@libs/actions/Session'), signOutAndRedirectToSignIn: jest.fn(), @@ -63,6 +116,14 @@ function renderBar(selectedTab: ValueOf) { ); } +function getSavedSidebarState() { + return Onyx.get(ONYXKEYS.NVP_SEARCH_SIDEBAR); +} + +function isStyleProp(value: unknown): value is StyleProp { + return value === undefined || value === null || typeof value === 'object'; +} + function getRow(name: string | RegExp) { return screen.getByRole(CONST.ROLE.TAB, {name}); } @@ -74,6 +135,12 @@ describe('FlatNavigationBar', () => { beforeEach(async () => { jest.clearAllMocks(); + mockCreateButtonProps = undefined; + mockIsElementHovered = false; + mockIsFocusMovingInside = false; + mockHasKeyboardFocusInside = false; + mockOuterHoverOut = undefined; + mockInnerHoverIn = undefined; mockInboxIndicator = NO_INDICATOR; mockWorkspacesIndicator = NO_INDICATOR; setIsSearchTabHovered(false); @@ -255,6 +322,360 @@ describe('FlatNavigationBar', () => { expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.SETTINGS); }); + describe('collapsing', () => { + function getBarWidth() { + const style: unknown = screen.getByTestId('FlatNavigationBar').props.style; + return isStyleProp(style) ? StyleSheet.flatten(style)?.width : undefined; + } + + it('collapses into a rail when the toggle is pressed and saves the state', async () => { + // Given the expanded bar + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + expect(getBarWidth()).toBe(variables.flatNavigationBarWidth); + + // When the toggle next to the logo is pressed + fireEvent.press(screen.getByRole(CONST.ROLE.BUTTON, {name: 'Collapse'})); + await waitForBatchedUpdatesWithAct(); + + // Then the bar narrows to the rail, the flag is saved for the next load, and the toggle now offers to expand + expect(getBarWidth()).toBe(variables.flatNavigationBarCollapsedWidth); + expect(await getSavedSidebarState()).toEqual({isCollapsed: true}); + expect(screen.getByRole(CONST.ROLE.BUTTON, {name: 'Expand'})).toBeOnTheScreen(); + }); + + it('renders collapsed on load when the saved state says so', async () => { + // Given a collapsed state saved by an earlier session + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + + // When the bar mounts + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + + // Then it is already the rail, so a reload does not flash the wide bar first + expect(getBarWidth()).toBe(variables.flatNavigationBarCollapsedWidth); + }); + + it('keeps every row reachable by its name while collapsed', async () => { + // Given a collapsed bar with the Inbox flagged for review + mockInboxIndicator = REVIEW_REQUIRED; + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + + // When the rows are read and one is pressed + fireEvent.press(getRow('Spend')); + + // Then the labels are still the rows' accessible names, since only their drawing fades, and a press still navigates + expect(getRow(`Inbox. ${REVIEW_REQUIRED_SUFFIX}`)).toBeOnTheScreen(); + expect(getRow('Workspaces')).toBeOnTheScreen(); + expect(mockNavigateToSearch).toHaveBeenCalledTimes(1); + expect(screen.getAllByTestId('FlatNavItemStatusIndicator')).toHaveLength(1); + }); + + it('disables logo pointer events and accessibility while collapsed', async () => { + // Given a collapsed bar + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + + // When the bar mounts + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + + // Then the logo container turns off pointer events and the logo button is disabled and hidden from accessibility + expect(screen.getByTestId('FlatNavLogoContainer').props.pointerEvents).toBe('none'); + + const logoButton = screen.getByTestId('ExpensifyLogoButton', {includeHiddenElements: true}); + expect(logoButton.props['aria-hidden']).toBe(true); + expect(logoButton.props.accessibilityState).toEqual(expect.objectContaining({disabled: true})); + }); + + it('keeps the bar peeking when hovering out while the create menu is open', async () => { + // Given a collapsed bar + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + + // When the pointer enters the items, which starts a peek + act(() => { + mockInnerHoverIn?.(); + }); + await waitForBatchedUpdatesWithAct(); + expect(getBarWidth()).toBe(variables.flatNavigationBarWidth); + + // And the Create menu opens + act(() => { + mockCreateButtonProps?.showCreateMenu?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // And the pointer leaves the bar (e.g. moving onto the popover) + act(() => { + mockOuterHoverOut?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the bar stays peeking so the menu does not collapse out from under the pointer + expect(getBarWidth()).toBe(variables.flatNavigationBarWidth); + + // When the menu closes and its modal is gone from the screen + act(() => { + mockCreateButtonProps?.hideCreateMenu?.(); + }); + act(() => { + mockCreateButtonProps?.onCreateMenuHidden?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the peek ends and the bar collapses back to a rail + expect(getBarWidth()).toBe(variables.flatNavigationBarCollapsedWidth); + }); + + it('keeps the bar peeking after the create menu closes if the pointer is still hovering the bar', async () => { + // Given a collapsed bar currently peeking with the Create menu open + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + + act(() => { + mockInnerHoverIn?.(); + }); + await waitForBatchedUpdatesWithAct(); + act(() => { + mockCreateButtonProps?.showCreateMenu?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // When the menu closes with the pointer still hovering over the bar + mockIsElementHovered = true; + act(() => { + mockCreateButtonProps?.hideCreateMenu?.(); + }); + act(() => { + mockCreateButtonProps?.onCreateMenuHidden?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the bar stays peeking because the cursor is still hovering over it + expect(getBarWidth()).toBe(variables.flatNavigationBarWidth); + + // When the pointer leaves the bar + mockIsElementHovered = false; + act(() => { + mockOuterHoverOut?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the peek ends and the bar collapses back to a rail + expect(getBarWidth()).toBe(variables.flatNavigationBarCollapsedWidth); + }); + + it('keeps the bar peeking after the create menu closes if an item has keyboard focus', async () => { + // Given a collapsed bar currently peeking with the Create menu open and no hover over the bar + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + + act(() => { + mockInnerHoverIn?.(); + }); + await waitForBatchedUpdatesWithAct(); + act(() => { + mockCreateButtonProps?.showCreateMenu?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // When the menu closes while an item inside the bar retains keyboard focus + mockIsElementHovered = false; + mockHasKeyboardFocusInside = true; + act(() => { + mockCreateButtonProps?.hideCreateMenu?.(); + }); + act(() => { + mockCreateButtonProps?.onCreateMenuHidden?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the bar stays peeking so the keyboard user still sees labels + expect(getBarWidth()).toBe(variables.flatNavigationBarWidth); + }); + + it('keeps the bar peeking while the closing create menu is still on screen', async () => { + // Given a collapsed bar currently peeking with the Create menu open and the pointer away from the bar + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + + act(() => { + mockInnerHoverIn?.(); + }); + await waitForBatchedUpdatesWithAct(); + act(() => { + mockCreateButtonProps?.showCreateMenu?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // When the menu starts closing, but its modal has not finished hiding yet + act(() => { + mockCreateButtonProps?.hideCreateMenu?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the bar stays peeking, because the modal's overlay still covers the bar and hides whether the pointer is on it + expect(getBarWidth()).toBe(variables.flatNavigationBarWidth); + }); + + it('keeps the bar peeking if the create menu reopens before the previous close finished', async () => { + // Given a collapsed bar currently peeking with the Create menu open + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + + act(() => { + mockInnerHoverIn?.(); + }); + await waitForBatchedUpdatesWithAct(); + act(() => { + mockCreateButtonProps?.showCreateMenu?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // When the menu closes, reopens, and only then reports the earlier close as finished + act(() => { + mockCreateButtonProps?.hideCreateMenu?.(); + }); + act(() => { + mockCreateButtonProps?.showCreateMenu?.(); + }); + act(() => { + mockCreateButtonProps?.onCreateMenuHidden?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the bar stays peeking under the open menu even though the pointer is not over it + expect(getBarWidth()).toBe(variables.flatNavigationBarWidth); + }); + + it('peeks the bar when items receive keyboard focus and collapses on blur', async () => { + // Given a collapsed bar + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + expect(getBarWidth()).toBe(variables.flatNavigationBarCollapsedWidth); + + // When navigation items gain focus via keyboard navigation + mockHasKeyboardFocusInside = true; + fireEvent(screen.getByTestId('FlatNavPeekBody'), 'focus'); + await waitForBatchedUpdatesWithAct(); + + // Then the bar peeks open to reveal labels for keyboard users + expect(getBarWidth()).toBe(variables.flatNavigationBarWidth); + + // When focus leaves the navigation items + mockHasKeyboardFocusInside = false; + fireEvent(screen.getByTestId('FlatNavPeekBody'), 'blur', { + nativeEvent: {}, + }); + await waitForBatchedUpdatesWithAct(); + + // Then the bar collapses back to a skinny rail + expect(getBarWidth()).toBe(variables.flatNavigationBarCollapsedWidth); + }); + + it('keeps the peek open when focus moves between items inside the bar', async () => { + // Given a collapsed bar peeking because an item has keyboard focus + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + mockHasKeyboardFocusInside = true; + fireEvent(screen.getByTestId('FlatNavPeekBody'), 'focus'); + await waitForBatchedUpdatesWithAct(); + + // When focus moves to another item inside the bar, e.g. tabbing from Home to Inbox + mockIsFocusMovingInside = true; + fireEvent(screen.getByTestId('FlatNavPeekBody'), 'blur', { + currentTarget: {}, + nativeEvent: {relatedTarget: {}}, + }); + await waitForBatchedUpdatesWithAct(); + + // Then the bar stays peeking, so its labels do not flicker on every Tab press + expect(getBarWidth()).toBe(variables.flatNavigationBarWidth); + }); + + it('keeps the peek open when the pointer leaves while an item has keyboard focus', async () => { + // Given a collapsed bar peeking because an item has keyboard focus + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + mockHasKeyboardFocusInside = true; + fireEvent(screen.getByTestId('FlatNavPeekBody'), 'focus'); + await waitForBatchedUpdatesWithAct(); + + // When the pointer passes over the bar and leaves it + act(() => { + mockOuterHoverOut?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the bar stays peeking, so the keyboard user still sees the label of the focused item + expect(getBarWidth()).toBe(variables.flatNavigationBarWidth); + }); + + it('collapses when the pointer leaves after an item was focused by a mouse click', async () => { + // Given a collapsed bar peeking under the pointer, with an item focused by a mouse click + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + act(() => { + mockInnerHoverIn?.(); + }); + await waitForBatchedUpdatesWithAct(); + fireEvent(screen.getByTestId('FlatNavPeekBody'), 'focus'); + await waitForBatchedUpdatesWithAct(); + + // When the pointer leaves the bar + act(() => { + mockOuterHoverOut?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // Then the bar collapses, because mouse focus must not hold it open + expect(getBarWidth()).toBe(variables.flatNavigationBarCollapsedWidth); + }); + + it('stays collapsed when the closing create menu hands focus back to its button without the keyboard', async () => { + // Given a collapsed bar that peeked under the pointer while the Create menu was open + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + renderBar(NAVIGATION_TABS.HOME); + await waitForBatchedUpdatesWithAct(); + act(() => { + mockInnerHoverIn?.(); + }); + await waitForBatchedUpdatesWithAct(); + act(() => { + mockCreateButtonProps?.showCreateMenu?.(); + }); + await waitForBatchedUpdatesWithAct(); + + // When the menu is dismissed with a click outside, which ends the peek once its modal is gone + act(() => { + mockCreateButtonProps?.hideCreateMenu?.(); + }); + act(() => { + mockCreateButtonProps?.onCreateMenuHidden?.(); + }); + await waitForBatchedUpdatesWithAct(); + expect(getBarWidth()).toBe(variables.flatNavigationBarCollapsedWidth); + + // And the modal then restores focus to the Create button, which is not keyboard focus + fireEvent(screen.getByTestId('FlatNavPeekBody'), 'focus'); + await waitForBatchedUpdatesWithAct(); + + // Then the bar stays collapsed, because only keyboard focus may start a peek + expect(getBarWidth()).toBe(variables.flatNavigationBarCollapsedWidth); + }); + }); + it('sends an anonymous user to sign in instead of Account', async () => { // Given an anonymous session await Onyx.set(ONYXKEYS.SESSION, {authTokenType: CONST.AUTH_TOKEN_TYPES.ANONYMOUS}); diff --git a/tests/ui/TabNavigatorBarFlatNavigationTest.tsx b/tests/ui/TabNavigatorBarFlatNavigationTest.tsx index e60b5dc57c5c..ab49c6d0c6d4 100644 --- a/tests/ui/TabNavigatorBarFlatNavigationTest.tsx +++ b/tests/ui/TabNavigatorBarFlatNavigationTest.tsx @@ -6,14 +6,18 @@ import useResponsiveLayout from '@hooks/useResponsiveLayout'; import TabNavigatorBar from '@libs/Navigation/AppNavigator/Navigators/TabNavigatorBar'; +import variables from '@styles/variables'; + import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import SCREENS from '@src/SCREENS'; import type {BottomTabBarProps} from '@react-navigation/bottom-tabs'; import type {ComponentType} from 'react'; +import type {StyleProp, ViewStyle} from 'react-native'; import React from 'react'; +import {StyleSheet} from 'react-native'; import Onyx from 'react-native-onyx'; import createMock from '../utils/createMock'; @@ -65,6 +69,10 @@ const tabBarState = createMock({ routes: [{key: 'home', name: SCREENS.HOME, params: undefined}], }); +function isStyleProp(value: unknown): value is StyleProp { + return value === undefined || value === null || typeof value === 'object'; +} + function mockLayout(shouldUseNarrowLayout: boolean) { jest.mocked(useResponsiveLayout).mockReturnValue(createMock>({shouldUseNarrowLayout})); } @@ -184,4 +192,41 @@ describe('TabNavigatorBar with the flatNav beta', () => { // Then the icon bar shows, because an override is the way to compare both navigations on the same account expectIconBar(); }); + + describe('container width', () => { + // The bar mocks render nothing of their own, so the container's style is found on the nearest ancestor that sets a width. + function getContainerWidth(testID: string) { + for (let node = screen.getByTestId(testID).parent; node; node = node.parent) { + const style: unknown = node.props.style; + const width = isStyleProp(style) ? StyleSheet.flatten(style)?.width : undefined; + if (width !== undefined) { + return width; + } + } + return undefined; + } + + it('follows the collapsed rail so the central pane moves with the bar', async () => { + // Given a user on the flatNav beta with the bar collapsed + await Onyx.set(ONYXKEYS.BETAS, [CONST.BETAS.FLAT_NAV]); + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + + // When the tab navigator draws its bar + await renderBar(); + + // Then the container reserves only the rail plus the sidebar next to it, which is what offsets the content + expect(getContainerWidth('FlatNavigationBar')).toBe(variables.flatNavigationBarCollapsedWidth + variables.sideBarWithLHBWidth); + }); + + it('keeps the icon bar width when the saved state is collapsed but the beta is off', async () => { + // Given the Spend sidebar collapsed on a user outside the beta + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + + // When the tab navigator draws its bar + await renderBar(); + + // Then the icon bar keeps its own width, so the flag changes nothing outside the beta + expect(getContainerWidth('NavigationTabBar')).toBe(variables.navigationTabBarSize + variables.sideBarWithLHBWidth); + }); + }); }); diff --git a/tests/unit/SearchSidebarCollapseStoreTest.tsx b/tests/unit/SearchSidebarCollapseStoreTest.tsx new file mode 100644 index 000000000000..750cc35fed9f --- /dev/null +++ b/tests/unit/SearchSidebarCollapseStoreTest.tsx @@ -0,0 +1,190 @@ +import {act, renderHook} from '@testing-library/react-native'; + +import {COLLAPSE_SURFACE, useSearchSidebarCollapse} from '@components/Navigation/SearchSidebarCollapseStore'; + +import ONYXKEYS from '@src/ONYXKEYS'; + +import Onyx from 'react-native-onyx'; + +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; + +function renderSurfaces() { + return renderHook(() => ({ + bar: useSearchSidebarCollapse(COLLAPSE_SURFACE.NAVIGATION_BAR), + spend: useSearchSidebarCollapse(), + })); +} + +describe('SearchSidebarCollapseStore', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + afterEach(async () => { + // The peek lives in module state, so a test that leaves one running would leak it into the next. + const {result, unmount} = renderSurfaces(); + act(() => { + result.current.bar.endPeek(); + result.current.spend.endPeek(); + }); + unmount(); + await act(async () => { + await Onyx.clear(); + await waitForBatchedUpdates(); + }); + }); + + it('collapses every surface from the one persisted flag', async () => { + // Given an expanded sidebar and both surfaces mounted + const {result} = renderSurfaces(); + await waitForBatchedUpdates(); + + // When the bar's toggle is pressed + await act(async () => { + result.current.bar.toggleSidebar(); + await waitForBatchedUpdates(); + }); + + // Then both the bar and the Spend column read the same flag, so they collapse together + expect(result.current.bar.isCollapsed).toBe(true); + expect(result.current.spend.isCollapsed).toBe(true); + }); + + it('reads a flag that was persisted before the surfaces mounted', async () => { + // Given a collapsed state saved by an earlier session, as after a page reload + await act(async () => { + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + await waitForBatchedUpdates(); + }); + + // When the surfaces mount + const {result} = renderSurfaces(); + await waitForBatchedUpdates(); + + // Then they start collapsed, with no toggle press needed + expect(result.current.bar.isVisuallyCollapsed).toBe(true); + expect(result.current.spend.isVisuallyCollapsed).toBe(true); + }); + + it('peeks only the surface the pointer is on', async () => { + // Given both surfaces collapsed + await act(async () => { + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + await waitForBatchedUpdates(); + }); + const {result} = renderSurfaces(); + await waitForBatchedUpdates(); + + // When the pointer enters the navigation bar + act(() => { + result.current.bar.startPeek(); + }); + + // Then the bar widens while the Spend column next to it stays collapsed + expect(result.current.bar.isPeeking).toBe(true); + expect(result.current.bar.isVisuallyCollapsed).toBe(false); + expect(result.current.spend.isPeeking).toBe(false); + expect(result.current.spend.isVisuallyCollapsed).toBe(true); + }); + + it('ignores a peek on another surface while one is already peeking', async () => { + // Given the bar peeking + await act(async () => { + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + await waitForBatchedUpdates(); + }); + const {result} = renderSurfaces(); + await waitForBatchedUpdates(); + act(() => { + result.current.bar.startPeek(); + }); + + // When the Spend column tries to peek too, and then ends its own peek + act(() => { + result.current.spend.startPeek(); + result.current.spend.endPeek(); + }); + + // Then the bar keeps peeking, because only the surface that started a peek can end it + expect(result.current.bar.isPeeking).toBe(true); + expect(result.current.spend.isPeeking).toBe(false); + }); + + it('does not peek an expanded surface', async () => { + // Given an expanded sidebar + const {result} = renderSurfaces(); + await waitForBatchedUpdates(); + + // When the pointer enters the bar + act(() => { + result.current.bar.startPeek(); + }); + + // Then nothing peeks, since there is nothing collapsed to widen + expect(result.current.bar.isPeeking).toBe(false); + }); + + it('ends the peek when the sidebar is toggled', async () => { + // Given the bar peeking over a collapsed sidebar + await act(async () => { + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + await waitForBatchedUpdates(); + }); + const {result} = renderSurfaces(); + await waitForBatchedUpdates(); + act(() => { + result.current.bar.startPeek(); + }); + + // When the toggle expands the sidebar + await act(async () => { + result.current.bar.toggleSidebar(); + await waitForBatchedUpdates(); + }); + + // Then the bar is expanded for good and no peek is left over to collapse it again later + expect(result.current.bar.isCollapsed).toBe(false); + expect(result.current.bar.isPeeking).toBe(false); + }); + + it('maintains a stable endPeek callback reference across renders', () => { + // Given a surface hook mounted + const {result, rerender} = renderHook(() => useSearchSidebarCollapse(COLLAPSE_SURFACE.NAVIGATION_BAR)); + const initialEndPeek = result.current.endPeek; + + // When the hook rerenders + rerender({}); + + // Then the endPeek reference is identical, so the bar's unmount cleanup that depends on it does not end a peek on every render + expect(result.current.endPeek).toBe(initialEndPeek); + }); + + it('does not re-render a surface when another surface peeks', async () => { + // Given both surfaces collapsed + await act(async () => { + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + await waitForBatchedUpdates(); + }); + const {result: barResult} = renderHook(() => useSearchSidebarCollapse(COLLAPSE_SURFACE.NAVIGATION_BAR)); + let spendRenderCount = 0; + renderHook(() => { + spendRenderCount++; + return useSearchSidebarCollapse(COLLAPSE_SURFACE.SEARCH_SIDEBAR); + }); + await waitForBatchedUpdates(); + const initialSpendRenderCount = spendRenderCount; + + // When the navigation bar peeks and collapses back + act(() => { + barResult.current.startPeek(); + }); + await waitForBatchedUpdates(); + act(() => { + barResult.current.endPeek(); + }); + await waitForBatchedUpdates(); + + // Then Spend consumers do not re-render because their peek snapshot boolean did not change + expect(spendRenderCount).toBe(initialSpendRenderCount); + }); +}); diff --git a/tests/unit/useNavigationBarWidthTest.tsx b/tests/unit/useNavigationBarWidthTest.tsx new file mode 100644 index 000000000000..519046f03921 --- /dev/null +++ b/tests/unit/useNavigationBarWidthTest.tsx @@ -0,0 +1,114 @@ +import {act, renderHook} from '@testing-library/react-native'; + +import useNavigationBarWidth from '@components/Navigation/FlatNavigationBar/useNavigationBarWidth'; +import {COLLAPSE_SURFACE, useSearchSidebarCollapse} from '@components/Navigation/SearchSidebarCollapseStore'; + +import variables from '@styles/variables'; + +import ONYXKEYS from '@src/ONYXKEYS'; + +import Onyx from 'react-native-onyx'; + +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; + +let mockShouldUseFlatNavigationBar = true; +jest.mock('@components/Navigation/FlatNavigationBar/useShouldUseFlatNavigationBar', () => ({ + __esModule: true, + default: () => mockShouldUseFlatNavigationBar, +})); + +describe('useNavigationBarWidth', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(() => { + mockShouldUseFlatNavigationBar = true; + }); + + afterEach(async () => { + // The peek lives in module state, so a test that leaves one running would leak it into the next. + const {result, unmount} = renderHook(() => useSearchSidebarCollapse(COLLAPSE_SURFACE.NAVIGATION_BAR)); + act(() => { + result.current.endPeek(); + }); + unmount(); + await act(async () => { + await Onyx.clear(); + await waitForBatchedUpdates(); + }); + }); + + it('returns the standard navigationTabBarSize when flat navigation is not active', () => { + // Given flat navigation disabled + mockShouldUseFlatNavigationBar = false; + + // When reading the navigation bar width + const {result} = renderHook(() => useNavigationBarWidth()); + + // Then it returns the classic icon bar width + expect(result.current).toBe(variables.navigationTabBarSize); + }); + + it('returns expanded width when flat navigation is active and not collapsed', async () => { + // Given flat navigation active and no collapsed state saved + + // When reading the navigation bar width + const {result} = renderHook(() => useNavigationBarWidth()); + await waitForBatchedUpdates(); + + // Then it returns the full flat navigation bar width + expect(result.current).toBe(variables.flatNavigationBarWidth); + }); + + it('returns collapsed width when flat navigation is collapsed', async () => { + // Given flat navigation collapsed in Onyx + await act(async () => { + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + await waitForBatchedUpdates(); + }); + + // When reading the navigation bar width + const {result} = renderHook(() => useNavigationBarWidth()); + await waitForBatchedUpdates(); + + // Then it returns the skinny rail width + expect(result.current).toBe(variables.flatNavigationBarCollapsedWidth); + }); + + it('does not re-render or change value when a surface starts or ends peeking', async () => { + // Given flat navigation collapsed + await act(async () => { + await Onyx.set(ONYXKEYS.NVP_SEARCH_SIDEBAR, {isCollapsed: true}); + await waitForBatchedUpdates(); + }); + + let renderCount = 0; + const {result} = renderHook(() => { + renderCount += 1; + return useNavigationBarWidth(); + }); + await waitForBatchedUpdates(); + const initialRenderCount = renderCount; + + // When peeking starts on the navigation bar + const {result: surfaceStore} = renderHook(() => useSearchSidebarCollapse(COLLAPSE_SURFACE.NAVIGATION_BAR)); + act(() => { + surfaceStore.current.startPeek(); + }); + await waitForBatchedUpdates(); + + // Then the width stays the collapsed layout width, since a peek overlays the content instead of pushing it, and the hook does not re-render + expect(result.current).toBe(variables.flatNavigationBarCollapsedWidth); + expect(renderCount).toBe(initialRenderCount); + + // When peeking ends + act(() => { + surfaceStore.current.endPeek(); + }); + await waitForBatchedUpdates(); + + // Then it still does not re-render + expect(renderCount).toBe(initialRenderCount); + }); +});