diff --git a/docs/6.x/docs/guides/_meta.json b/docs/6.x/docs/guides/_meta.json index 11525283c4..e7c2e3d42b 100644 --- a/docs/6.x/docs/guides/_meta.json +++ b/docs/6.x/docs/guides/_meta.json @@ -7,7 +7,7 @@ "recommended-libraries", "contributing", "theming-with-react-navigation", - "bottom-navigation", + "navigation-bar", "react-navigation", "rtl", "ripple-effect", diff --git a/docs/6.x/docs/guides/migration.md b/docs/6.x/docs/guides/migration.md index 155a18f11d..62d86d3969 100644 --- a/docs/6.x/docs/guides/migration.md +++ b/docs/6.x/docs/guides/migration.md @@ -161,8 +161,7 @@ Hardcoded default test IDs have been removed for the components listed below: - `AnimatedFAB`: `animated-fab` - `Appbar.Content`: `appbar-content` - `Appbar.Header`: `appbar-header` -- `BottomNavigation`: `bottom-navigation` -- `BottomNavigation.Bar`: `bottom-navigation-bar` +- `BottomNavigation` and `BottomNavigation.Bar`: `bottom-navigation` and `bottom-navigation-bar`. Both components are removed, see [BottomNavigation](#bottomnavigation). - `Button`: `button` - `Card`: `card` - `Chip`: `chip` @@ -185,7 +184,6 @@ If you were relying on internal test IDs, update your tests not to rely on inter Some components now accept explicit `testID` props for their interactable elements: -- `BottomNavigation`: `barTestID` for the internal `BottomNavigation.Bar`, replacing the previous `${testID}-bar` derivation. - `Chip`: `closeIconTestID` for the close icon button. - `Dialog` and `Modal`: `overlayTestID` for the overlay displayed behind the content. - `Menu`: `overlayTestID` for the overlay displayed behind the menu. @@ -412,7 +410,7 @@ Components now use React Native's `aria-*` props and `role` instead of the `acce Props that label a part of a component keep their names, e.g. `closeIconAccessibilityLabel` on `Chip` and `dismissAccessibilityLabel` on `Modal`. -Keys inside data objects changed the same way: the `routes` of `BottomNavigation` and the `buttons` of `SegmentedButtons` now take `'aria-label'`. The old `accessibilityLabel` key is ignored, and TypeScript doesn't report it in `routes`. +Keys inside data objects changed the same way: the `routes` of `NavigationBar` (`BottomNavigation` in 5.x) and the `buttons` of `SegmentedButtons` now take `'aria-label'`. The old `accessibilityLabel` key is ignored, and TypeScript doesn't report it in `routes`. ```diff ``` +### BottomNavigation + +`BottomNavigation` has been removed. Paper no longer ships a component that owns your tab scenes; the Material 3 navigation bar is now `NavigationBar`, a standalone bar you render next to your own navigator (React Navigation, or your own state). + +| v5 | v6 | +| --------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| `BottomNavigation`, `BottomNavigation.Bar` | `NavigationBar` | +| `BottomNavigationProps`, `BottomNavigationRoute` | `NavigationBarProps`, `NavigationBarRoute` | +| `BottomNavigation.SceneMap`, `renderScene`, `onIndexChange` | render the active scene yourself, alongside the bar | +| `getLazy`, `route.lazy` | removed (the bar no longer owns the scenes) | +| `sceneAnimationEnabled`, `sceneAnimationType`, `sceneAnimationEasing` | removed with the scene container | +| `shifting` | removed (including the active-icon shift and inactive-label transitions) | +| `barStyle` | `style` | +| `style` (the whole `BottomNavigation`, scenes and bar) | wrap your scenes and the bar in your own `View` (`style` styles the bar) | +| `animationEasing` | removed (the indicator uses M3 motion from the theme) | +| `barStyle` with `Animated.Value` | `style` with static styles only | +| `barTestID`, `${testID}-bar` | `testID` on `NavigationBar` | +| n/a | new `variant` (`'stacked' \| 'horizontal'`) for the item layout | + +The bar is 64dp tall instead of 80dp, which is the height of the M3 flexible navigation bar. If your app moves a `FAB` or a `Snackbar` up by the height of the bar, change that offset. The label of the active tab uses `secondary` instead of `onSurface`. + +```diff ++ const scenes = { home: HomeScreen, settings: SettingsScreen }; ++ const ActiveScene = scenes[routes[index].key]; ++ +- ++ <> ++ ++ setIndex(routes.findIndex((r) => r.key === route.key))} ++ /> ++ +``` + +This renders only the active route, so a screen unmounts when you leave its tab, unlike v5 which kept the visited screens mounted. If your app depends on that state, render `NavigationBar` as the [`tabBar` of React Navigation's bottom tabs](./navigation-bar#quick-example), which keeps screens mounted. + +`onTabPress` & `onTabLongPress` callbacks receive only pressed `route`. The v5 event object also carried `preventDefault()` & `defaultPrevented`, so code that reads them now throws `preventDefault is not a function`. The bar never navigates on its own, so navigator's own `tabPress` event decides whether press is handled: + +```diff + tabBar={({ navigation, state, descriptors, insets }) => ( + { ++ onTabPress={({ route }) => { + const event = navigation.emit({ + type: 'tabPress', + target: route.key, + canPreventDefault: true, + }); + +- if (event.defaultPrevented) { +- preventDefault(); +- } else { ++ if (!event.defaultPrevented) { + navigation.dispatch({ + ...CommonActions.navigate(route.name, route.params), + target: state.key, + }); + } + }} + /> + )} +``` + +The `animationEasing` prop is gone along with animation it configured. Active indicator now follows the motion from theme (`theme.motion`) and honors reduce motion preference. + +Unlike v5 `barStyle`, the `style` prop no longer accepts `Animated.Value` or `Animated.AnimatedInterpolation`. Pass static styles. + +`NavigationBar` also does not set a default `testID`. If your tests looked up `bottom-navigation-bar` (or its `-container` / `-content` / `-content-wrapper` children), pass a `testID` explicitly. + ### Surface - The `elevation` prop no longer accepts a React Native `Animated.Value`. Any `elevation` changes are animated automatically. @@ -2124,7 +2198,7 @@ const TertiarySwitch = ({ `Icon`'s `source` prop is typed as `IconSource` instead of `any`, so a value that isn't an icon name, an image source or a render function, such as a boolean or `undefined`, is now a type error. `Icon` still renders nothing for those values. -If you pass a field that can be `undefined`, such as an optional `focusedIcon` on a route in `BottomNavigation`'s `renderIcon`, check it first: +If you pass a field that can be `undefined`, such as an optional `focusedIcon` on a route in `NavigationBar`'s `renderIcon`, check it first: ```diff -renderIcon={({ route, color }) => ( diff --git a/docs/6.x/docs/guides/bottom-navigation.md b/docs/6.x/docs/guides/navigation-bar.md similarity index 77% rename from docs/6.x/docs/guides/bottom-navigation.md rename to docs/6.x/docs/guides/navigation-bar.md index 06f9c3f996..c63fc2eadb 100644 --- a/docs/6.x/docs/guides/bottom-navigation.md +++ b/docs/6.x/docs/guides/navigation-bar.md @@ -1,13 +1,11 @@ --- -title: Using BottomNavigation with React Navigation +title: Using NavigationBar with React Navigation --- Build a Material Design bottom tab bar by combining two pieces: - `@react-navigation/bottom-tabs` handles routing, state, and screen options. -- `BottomNavigation.Bar` renders the Material 3 tab bar (ripple, badges, shifting/labeled modes). - - +- `NavigationBar` renders the Material 3 navigation bar (state layers, badges, and stacked or horizontal item layouts). :::info Install [`@react-navigation/native`](https://reactnavigation.org/docs/getting-started) and [`@react-navigation/bottom-tabs`](https://reactnavigation.org/docs/bottom-tab-navigator) first. @@ -15,13 +13,13 @@ Install [`@react-navigation/native`](https://reactnavigation.org/docs/getting-st ## Quick example -Pass a `BottomNavigation.Bar` to the navigator's `tabBar` prop. The bar reads navigation state and dispatches `tabPress` events back: +Pass a `NavigationBar` to the navigator's `tabBar` prop. The bar reads navigation state and dispatches `tabPress` events back: ```tsx import MaterialCommunityIcons from '@react-native-vector-icons/material-design-icons'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { CommonActions } from '@react-navigation/native'; -import { BottomNavigation } from 'react-native-paper'; +import { NavigationBar } from 'react-native-paper'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; const Tab = createBottomTabNavigator(); @@ -31,20 +29,17 @@ function MyTabs() { return ( ( - { + onTabPress={({ route }) => { const event = navigation.emit({ type: 'tabPress', target: route.key, canPreventDefault: true, }); - if (event.defaultPrevented) { - preventDefault(); - } else { + if (!event.defaultPrevented) { navigation.dispatch({ ...CommonActions.navigate(route.name, route.params), target: state.key, diff --git a/docs/6.x/docs/guides/theming.mdx b/docs/6.x/docs/guides/theming.mdx index f12ef73f2b..ff10e71408 100644 --- a/docs/6.x/docs/guides/theming.mdx +++ b/docs/6.x/docs/guides/theming.mdx @@ -592,7 +592,7 @@ 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 `Appbar` or `NavigationBar`.
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. 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 73ebb3b3b2..8cf33870d2 100644 --- a/docs/component-docs.config.ts +++ b/docs/component-docs.config.ts @@ -46,10 +46,6 @@ const pages = { }, Badge: 'Badge', Banner: 'Banner', - BottomNavigation: { - BottomNavigation: 'BottomNavigation/BottomNavigation', - BottomNavigationBar: 'BottomNavigation/BottomNavigationBar', - }, Button: { Button: 'Button/Button', }, @@ -110,6 +106,9 @@ const pages = { MenuItem: 'Menu/MenuItem', }, Modal: 'Modal', + NavigationBar: { + NavigationBar: 'NavigationBar/NavigationBar', + }, Portal: { Portal: { source: 'Portal/Portal', diff --git a/docs/public/screenshots/navigation-bar.png b/docs/public/screenshots/navigation-bar.png new file mode 100644 index 0000000000..7e6b1b4173 Binary files /dev/null and b/docs/public/screenshots/navigation-bar.png differ diff --git a/docs/src/data/extendedExamples.ts b/docs/src/data/extendedExamples.ts index 20800e2005..f37722c307 100644 --- a/docs/src/data/extendedExamples.ts +++ b/docs/src/data/extendedExamples.ts @@ -1,10 +1,7 @@ -import { - dynamicCode, - staticCode, -} from './extendedExamples/BottomNavigationBar.ts'; +import { dynamicCode, staticCode } from './extendedExamples/NavigationBar.ts'; export const extendedExamples = { - 'BottomNavigation.Bar': { + NavigationBar: { 'with React Navigation': { static: staticCode, dynamic: dynamicCode, diff --git a/docs/src/data/extendedExamples/BottomNavigationBar.ts b/docs/src/data/extendedExamples/NavigationBar.ts similarity index 88% rename from docs/src/data/extendedExamples/BottomNavigationBar.ts rename to docs/src/data/extendedExamples/NavigationBar.ts index 7a49db0bce..718b0e3d56 100644 --- a/docs/src/data/extendedExamples/BottomNavigationBar.ts +++ b/docs/src/data/extendedExamples/NavigationBar.ts @@ -1,6 +1,6 @@ export const staticCode = `import { Text, View } from 'react-native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; -import { Provider, BottomNavigation } from 'react-native-paper'; +import { Provider, NavigationBar } from 'react-native-paper'; import MaterialCommunityIcons from '@react-native-vector-icons/material-design-icons'; import { CommonActions, @@ -24,23 +24,18 @@ function SettingsScreen() { } const MyTabs = createBottomTabNavigator({ - screenOptions: { - animation: 'shift', - }, tabBar: ({ navigation, state, descriptors, insets }) => ( - { + onTabPress={({ route }) => { const event = navigation.emit({ type: 'tabPress', target: route.key, canPreventDefault: true, }); - if (event.defaultPrevented) { - preventDefault(); - } else { + if (!event.defaultPrevented) { navigation.dispatch({ ...CommonActions.navigate(route.name, route.params), target: state.key, @@ -102,7 +97,7 @@ export default function App() { export const dynamicCode = `import { Text, View } from 'react-native'; import { NavigationContainer, CommonActions } from '@react-navigation/native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; -import { Provider, BottomNavigation } from 'react-native-paper'; +import { Provider, NavigationBar } from 'react-native-paper'; import MaterialCommunityIcons from '@react-native-vector-icons/material-design-icons'; function HomeScreen() { @@ -128,23 +123,18 @@ export default function App() { ( - { + onTabPress={({ route }) => { const event = navigation.emit({ type: 'tabPress', target: route.key, canPreventDefault: true, }); - if (event.defaultPrevented) { - preventDefault(); - } else { + if (!event.defaultPrevented) { navigation.dispatch({ ...CommonActions.navigate(route.name, route.params), target: state.key, diff --git a/docs/src/data/screenshots.ts b/docs/src/data/screenshots.ts index e18135fc49..e0b42ab802 100644 --- a/docs/src/data/screenshots.ts +++ b/docs/src/data/screenshots.ts @@ -19,8 +19,6 @@ export const screenshots = { dot: 'screenshots/badge-3.png', }, Banner: 'screenshots/banner.gif', - BottomNavigation: 'screenshots/bottom-navigation.gif', - 'BottomNavigation.Bar': 'screenshots/bottom-navigation-tabs.jpg', Button: { filled: 'screenshots/button-3.png', tonal: 'screenshots/button-5.png', @@ -112,6 +110,7 @@ export const screenshots = { }, 'Menu.Item': 'screenshots/menu-item.png', Modal: 'screenshots/modal.gif', + NavigationBar: 'screenshots/navigation-bar.png', ProgressBar: 'screenshots/progress-bar.png', RadioButton: { 'Android (enabled)': 'screenshots/radio-enabled.android.png', diff --git a/docs/src/data/versionRouteFallbacks.json b/docs/src/data/versionRouteFallbacks.json index fc8c088238..6b9593d429 100644 --- a/docs/src/data/versionRouteFallbacks.json +++ b/docs/src/data/versionRouteFallbacks.json @@ -1,5 +1,7 @@ { "next": { + "/docs/components/BottomNavigation/BottomNavigation": "/6.x/docs/components/NavigationBar/NavigationBar", + "/docs/components/BottomNavigation/BottomNavigationBar": "/6.x/docs/components/NavigationBar/NavigationBar", "/docs/components/Checkbox/CheckboxAndroid": "/6.x/docs/components/Checkbox/Checkbox", "/docs/components/Checkbox/CheckboxIOS": "/6.x/docs/components/Checkbox/Checkbox", "/docs/components/Dialog/DialogActions": "/6.x/docs/components/Dialog/Dialog", @@ -14,12 +16,15 @@ "/docs/components/ToggleButton/ToggleButton": "/6.x/docs/guides/migration#togglebutton", "/docs/components/ToggleButton/ToggleButtonGroup": "/6.x/docs/guides/migration#togglebutton", "/docs/components/ToggleButton/ToggleButtonRow": "/6.x/docs/guides/migration#togglebutton", + "/docs/guides/bottom-navigation": "/6.x/docs/guides/navigation-bar", "/docs/guides/migration-guide-to-5.0": "/6.x/docs/guides/migration" }, "stable": { "/6.x/docs/components/FAB/FABExtended": "/docs/components/FAB/FAB", "/6.x/docs/components/FAB/FABMenu": "/docs/components/FAB/FAB", + "/6.x/docs/components/NavigationBar/NavigationBar": "/docs/components/BottomNavigation/BottomNavigationBar", "/6.x/docs/guides/migration": "/docs/guides/migration-guide-to-5.0", + "/6.x/docs/guides/navigation-bar": "/docs/guides/bottom-navigation", "/6.x/docs/guides/rtl": "/" } } diff --git a/example/src/ExampleList.tsx b/example/src/ExampleList.tsx index e5089029ad..2484cce17d 100644 --- a/example/src/ExampleList.tsx +++ b/example/src/ExampleList.tsx @@ -9,8 +9,6 @@ import AppbarExample from './Examples/AppbarExample'; import AvatarExample from './Examples/AvatarExample'; import BadgeExample from './Examples/BadgeExample'; import BannerExample from './Examples/BannerExample'; -import BottomNavigationBarExample from './Examples/BottomNavigationBarExample'; -import BottomNavigationExample from './Examples/BottomNavigationExample'; import ButtonExample from './Examples/ButtonExample'; import CardExample from './Examples/CardExample'; import CheckboxExample from './Examples/CheckboxExample'; @@ -28,6 +26,8 @@ import ListAccordionExampleGroup from './Examples/ListAccordionGroupExample'; import ListItemExample from './Examples/ListItemExample'; import ListSectionExample from './Examples/ListSectionExample'; import MenuExample from './Examples/MenuExample'; +import NavigationBarExample from './Examples/NavigationBarExample'; +import NavigationBarReactNavigationExample from './Examples/NavigationBarReactNavigationExample'; import ProgressBarExample from './Examples/ProgressBarExample'; import RadioButtonExample from './Examples/RadioButtonExample'; import RadioButtonGroupExample from './Examples/RadioButtonGroupExample'; @@ -54,8 +54,7 @@ export const mainExamples = { Avatar: AvatarExample, Badge: BadgeExample, Banner: BannerExample, - BottomNavigationBarExample, - BottomNavigation: BottomNavigationExample, + NavigationBarReactNavigationExample, Button: ButtonExample, Card: CardExample, Checkbox: CheckboxExample, @@ -73,6 +72,7 @@ export const mainExamples = { ListSection: ListSectionExample, ListItem: ListItemExample, Menu: MenuExample, + NavigationBar: NavigationBarExample, Progressbar: ProgressBarExample, Radio: RadioButtonExample, RadioGroup: RadioButtonGroupExample, diff --git a/example/src/Examples/BottomNavigationExample.tsx b/example/src/Examples/BottomNavigationExample.tsx deleted file mode 100644 index b66bb474d6..0000000000 --- a/example/src/Examples/BottomNavigationExample.tsx +++ /dev/null @@ -1,188 +0,0 @@ -import * as React from 'react'; -import { - Dimensions, - Easing, - Image, - Platform, - StyleSheet, - View, -} from 'react-native'; - -import { useNavigation } from '@react-navigation/native'; -import { Appbar, BottomNavigation, Menu } from 'react-native-paper'; -import type { BottomNavigationRoute } from 'react-native-paper'; -import { useSafeAreaInsets } from 'react-native-safe-area-context'; - -import ScreenWrapper from '../ScreenWrapper'; - -type Route = { route: { key: string } }; - -const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical'; - -const PhotoGallery = ({ route }: Route) => { - const PHOTOS = Array.from({ length: 24 }).map( - (_, i) => `https://unsplash.it/300/300/?random&__id=${route.key}${i}` - ); - - return ( - - {PHOTOS.map((uri) => ( - - - - ))} - - ); -}; - -const BottomNavigationExample = () => { - const navigation = useNavigation('BottomNavigation'); - - const insets = useSafeAreaInsets(); - const [index, setIndex] = React.useState(0); - const [menuVisible, setMenuVisible] = React.useState(false); - const [sceneAnimation, setSceneAnimation] = - React.useState< - React.ComponentProps['sceneAnimationType'] - >(); - - const [routes] = React.useState([ - { - key: 'album', - title: 'Album', - focusedIcon: 'image-album', - }, - { - key: 'library', - title: 'Library', - focusedIcon: 'inbox', - unfocusedIcon: 'inbox-outline', - badge: true, - }, - { - key: 'favorites', - title: 'Favorites', - focusedIcon: 'heart', - unfocusedIcon: 'heart-outline', - }, - { - key: 'purchased', - title: 'Purchased', - focusedIcon: 'shopping', - unfocusedIcon: 'shopping-outline', - }, - ]); - - React.useLayoutEffect(() => { - navigation.setOptions({ - headerShown: false, - }); - }, [navigation]); - - 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" - /> - - - route.key !== 'album'} - /> - - ); -}; - -BottomNavigationExample.title = 'Bottom Navigation'; - -export default BottomNavigationExample; - -const styles = StyleSheet.create({ - ...Platform.select({ - web: { - content: { - // there is no 'grid' type in RN :( - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - display: 'grid' as 'none', - gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', - gridRowGap: '8px', - gridColumnGap: '8px', - padding: 8, - }, - item: { - width: '100%', - height: 150, - }, - }, - default: { - content: { - flexDirection: 'row', - flexWrap: 'wrap', - padding: 4, - }, - item: { - height: Dimensions.get('window').width / 2, - width: '50%', - padding: 4, - }, - }, - }), - photo: { - flex: 1, - }, - screen: { - flex: 1, - }, -}); diff --git a/example/src/Examples/NavigationBarExample.tsx b/example/src/Examples/NavigationBarExample.tsx new file mode 100644 index 0000000000..bfa4dc5b04 --- /dev/null +++ b/example/src/Examples/NavigationBarExample.tsx @@ -0,0 +1,110 @@ +import * as React from 'react'; +import { StyleSheet, View, useWindowDimensions } from 'react-native'; + +import { + NavigationBar, + SegmentedButtons, + Switch, + Text, +} from 'react-native-paper'; + +type VariantMode = 'auto' | 'stacked' | 'horizontal'; + +// The flexible navigation bar switches to a horizontal item arrangement in +// medium-width windows. M3 recommends ~600dp as the breakpoint, but the +// component leaves the decision to the consumer — here it is driven by +// `useWindowDimensions`. +const MEDIUM_WINDOW_WIDTH = 600; + +const routes = [ + { key: 'album', title: 'Album', focusedIcon: 'image-album', badge: 3 }, + { key: 'library', title: 'Library', focusedIcon: 'bookshelf' }, + { + key: 'favorites', + title: 'Favorites', + focusedIcon: 'heart', + unfocusedIcon: 'heart-outline', + }, + { + key: 'settings', + title: 'Settings', + focusedIcon: 'cog', + unfocusedIcon: 'cog-outline', + }, +]; + +const NavigationBarExample = () => { + const [index, setIndex] = React.useState(0); + const [labeled, setLabeled] = React.useState(true); + const [variantMode, setVariantMode] = React.useState('auto'); + + const { width } = useWindowDimensions(); + const autoVariant = width >= MEDIUM_WINDOW_WIDTH ? 'horizontal' : 'stacked'; + const variant = variantMode === 'auto' ? autoVariant : variantMode; + + return ( + + + {routes[index].title} + + + + Show labels + + + + + + + + { + const nextIndex = routes.findIndex( + (tabRoute) => tabRoute.key === route.key + ); + if (nextIndex !== -1) { + setIndex(nextIndex); + } + }} + /> + + ); +}; + +NavigationBarExample.title = 'Navigation Bar (flexible)'; + +export default NavigationBarExample; + +const styles = StyleSheet.create({ + container: { + flex: 1, + }, + content: { + flex: 1, + justifyContent: 'center', + alignItems: 'center', + padding: 16, + }, + controls: { + marginTop: 32, + width: '100%', + maxWidth: 480, + gap: 24, + }, + row: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + }, +}); diff --git a/example/src/Examples/BottomNavigationBarExample.tsx b/example/src/Examples/NavigationBarReactNavigationExample.tsx similarity index 89% rename from example/src/Examples/BottomNavigationBarExample.tsx rename to example/src/Examples/NavigationBarReactNavigationExample.tsx index fa73112c86..d0cfd76fb6 100644 --- a/example/src/Examples/BottomNavigationBarExample.tsx +++ b/example/src/Examples/NavigationBarReactNavigationExample.tsx @@ -11,7 +11,7 @@ import { SFSymbol, MaterialSymbol, } from '@react-navigation/native'; -import { Text, BottomNavigation } from 'react-native-paper'; +import { Text, NavigationBar } from 'react-native-paper'; function HomeScreen() { return ( @@ -29,14 +29,14 @@ function SettingsScreen() { ); } -const BottomNavigationBarExample = createBottomTabNavigator({ +const NavigationBarReactNavigationExample = createBottomTabNavigator({ screenOptions: { headerShown: false, }, tabBar: ({ navigation, state, descriptors }) => ( - { + onTabPress={({ route }) => { const isRepeatedPress = state.routes[state.index].key === route.key; const event = navigation.emit({ type: 'tabPress', @@ -50,9 +50,7 @@ const BottomNavigationBarExample = createBottomTabNavigator({ }, }); - if (event.defaultPrevented) { - preventDefault(); - } else { + if (!event.defaultPrevented) { // Custom tab bars must target the tab navigator state. navigation.dispatch({ ...CommonActions.navigate(route.name, route.params), @@ -125,8 +123,8 @@ const BottomNavigationBarExample = createBottomTabNavigator({ }, }); -export default Object.assign(BottomNavigationBarExample, { - title: 'Bottom Navigation Bar', +export default Object.assign(NavigationBarReactNavigationExample, { + title: 'Navigation Bar (React Navigation)', }); const styles = StyleSheet.create({ diff --git a/example/src/Examples/TeamDetails.tsx b/example/src/Examples/TeamDetails.tsx index cb06e817d6..6618ff78e6 100644 --- a/example/src/Examples/TeamDetails.tsx +++ b/example/src/Examples/TeamDetails.tsx @@ -1,6 +1,5 @@ import * as React from 'react'; import { - Easing, FlatList, ScrollView, StyleSheet, @@ -11,7 +10,7 @@ import { import { useNavigation, useRoute } from '@react-navigation/native'; import { Appbar, - BottomNavigation, + NavigationBar, Card, Button, Text, @@ -219,20 +218,21 @@ const ThemeBasedOnSourceColor = () => { navigation.goBack()} /> - + {routes[index].key === 'news' && } + {routes[index].key === 'results' && } + {routes[index].key === 'roster' && } + + { + const nextIndex = routes.findIndex( + (tabRoute) => tabRoute.key === route.key + ); + if (nextIndex !== -1 && nextIndex !== index) setIndex(nextIndex); + }} labelMaxFontSizeMultiplier={2} - renderScene={BottomNavigation.SceneMap({ - news: News, - results: Results, - roster: Roster, - })} - sceneAnimationEnabled - sceneAnimationType={'opacity'} - sceneAnimationEasing={Easing.ease} - getLazy={({ route }) => route.key !== 'album'} /> @@ -247,6 +247,9 @@ const styles = StyleSheet.create({ screen: { flex: 1, }, + scene: { + flex: 1, + }, winner: { fontWeight: '700', }, diff --git a/src/babel/__fixtures__/rewrite-imports/code.js b/src/babel/__fixtures__/rewrite-imports/code.js index f1253a5e08..ed1032e772 100644 --- a/src/babel/__fixtures__/rewrite-imports/code.js +++ b/src/babel/__fixtures__/rewrite-imports/code.js @@ -1,7 +1,7 @@ /* eslint-disable prettier/prettier */ import { PaperProvider, - BottomNavigation, + NavigationBar, Button, FAB, Appbar, diff --git a/src/babel/__fixtures__/rewrite-imports/output.js b/src/babel/__fixtures__/rewrite-imports/output.js index bbe342ad0d..c98769872b 100644 --- a/src/babel/__fixtures__/rewrite-imports/output.js +++ b/src/babel/__fixtures__/rewrite-imports/output.js @@ -1,6 +1,6 @@ /* eslint-disable prettier/prettier */ import PaperProvider from "react-native-paper/lib/module/core/PaperProvider"; -import BottomNavigation from "react-native-paper/lib/module/components/BottomNavigation/BottomNavigation"; +import NavigationBar from "react-native-paper/lib/module/components/NavigationBar"; import Button from "react-native-paper/lib/module/components/Button/Button"; import FAB from "react-native-paper/lib/module/components/FAB"; import Appbar from "react-native-paper/lib/module/components/Appbar"; diff --git a/src/components/BottomNavigation/BottomNavigation.tsx b/src/components/BottomNavigation/BottomNavigation.tsx deleted file mode 100644 index b391336256..0000000000 --- a/src/components/BottomNavigation/BottomNavigation.tsx +++ /dev/null @@ -1,632 +0,0 @@ -import * as React from 'react'; -// eslint-disable-next-line no-restricted-imports -- TODO: migrate BottomNavigation to Reanimated. -import { Animated, Platform, StyleSheet, View } from 'react-native'; -import type { - ColorValue, - EasingFunction, - StyleProp, - ViewStyle, -} from 'react-native'; - -import useLatestCallback from 'use-latest-callback'; - -import BottomNavigationBar from './BottomNavigationBar'; -import BottomNavigationRouteScreen from './BottomNavigationRouteScreen'; -import { useInternalTheme } from '../../core/theming'; -import { useMotionDuration } from '../../theme/accessibility/ReduceMotionContext'; -import type { ThemeProp } from '../../theme/types'; -import useAnimatedValueArray from '../../utils/useAnimatedValueArray'; -import type { IconSource } from '../Icon'; -import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple'; - -export type BaseRoute = { - key: string; - title?: string; - focusedIcon?: IconSource; - unfocusedIcon?: IconSource; - badge?: string | number | boolean; - 'aria-label'?: string; - testID?: string; - lazy?: boolean; -}; - -type NavigationState = { - index: number; - routes: Route[]; -}; - -type TabPressEvent = { - defaultPrevented: boolean; - preventDefault(): void; -}; - -type TouchableProps = TouchableRippleProps & { - key: string; - route: Route; - children: React.ReactNode; - borderless?: boolean; - centered?: boolean; - rippleColor?: ColorValue; -}; - -export type Props = { - /** - * Whether the shifting style is used, the active tab icon shifts up to show the label and the inactive tabs won't have a label. - * - * By default, this is `false` with theme version 3 and `true` when you have more than 3 tabs. - * Pass `shifting={false}` to explicitly disable this animation, or `shifting={true}` to always use this animation. - * Note that you need at least 2 tabs be able to run this animation. - */ - shifting?: boolean; - /** - * Whether to show labels in tabs. When `false`, only icons will be displayed. - */ - labeled?: boolean; - /** - * Whether tabs should be spread across the entire width. - */ - compact?: boolean; - /** - * State for the bottom navigation. The state should contain the following properties: - * - * - `index`: a number representing the index of the active route in the `routes` array - * - `routes`: an array containing a list of route objects used for rendering the tabs - * - * Each route object should contain the following properties: - * - * - `key`: a unique key to identify the route (required) - * - `title`: title of the route to use as the tab label - * - `focusedIcon`: icon to use as the focused tab icon, can be a string, an image source or a react component @renamed Renamed from 'icon' to 'focusedIcon' in v5.x - * - `unfocusedIcon`: icon to use as the unfocused tab icon, can be a string, an image source or a react component @supported Available in v5.x with theme version 3 - * - `badge`: badge to show on the tab icon, can be `true` to show a dot, `string` or `number` to show text. - * - `aria-label`: accessibility label for the tab button - * - `testID`: test id for the tab button - * - * Example: - * - * ```js - * { - * index: 1, - * routes: [ - * { key: 'music', title: 'Favorites', focusedIcon: 'heart', unfocusedIcon: 'heart-outline'}, - * { key: 'albums', title: 'Albums', focusedIcon: 'album' }, - * { key: 'recents', title: 'Recents', focusedIcon: 'history' }, - * { key: 'notifications', title: 'Notifications', focusedIcon: 'bell', unfocusedIcon: 'bell-outline' }, - * ] - * } - * ``` - * - * `BottomNavigation` is a controlled component, which means the `index` needs to be updated via the `onIndexChange` callback. - */ - navigationState: NavigationState; - /** - * Callback which is called on tab change, receives the index of the new tab as argument. - * The navigation state needs to be updated when it's called, otherwise the change is dropped. - */ - onIndexChange: (index: number) => void; - /** - * Callback which returns a react element to render as the page for the tab. Receives an object containing the route as the argument: - * - * ```js - * renderScene = ({ route, jumpTo }) => { - * switch (route.key) { - * case 'music': - * return ; - * case 'albums': - * return ; - * } - * } - * ``` - * - * Pages are lazily rendered, which means that a page will be rendered the first time you navigate to it. - * After initial render, all the pages stay rendered to preserve their state. - * - * You need to make sure that your individual routes implement a `shouldComponentUpdate` to improve the performance. - * To make it easier to specify the components, you can use the `SceneMap` helper: - * - * ```js - * renderScene = BottomNavigation.SceneMap({ - * music: MusicRoute, - * albums: AlbumsRoute, - * }); - * ``` - * - * Specifying the components this way is easier and takes care of implementing a `shouldComponentUpdate` method. - * Each component will receive the current route and a `jumpTo` method as it's props. - * The `jumpTo` method can be used to navigate to other tabs programmatically: - * - * ```js - * this.props.jumpTo('albums') - * ``` - */ - renderScene: (props: { - route: Route; - jumpTo: (key: string) => void; - }) => React.ReactNode | null; - /** - * Callback which returns a React Element to be used as tab icon. - */ - renderIcon?: (props: { - route: Route; - focused: boolean; - color: ColorValue; - }) => React.ReactNode; - /** - * Callback which React Element to be used as tab label. - */ - renderLabel?: (props: { - route: Route; - focused: boolean; - color: ColorValue; - }) => React.ReactNode; - /** - * Callback which returns a React element to be used as the touchable for the tab item. - * Renders a `TouchableRipple` on Android and `Pressable` on iOS. - */ - renderTouchable?: (props: TouchableProps) => React.ReactNode; - /** - * Get accessibility label for the tab button. This is read by the screen reader when the user taps the tab. - * Uses `route['aria-label']` by default. - */ - getAccessibilityLabel?: (props: { route: Route }) => string | undefined; - /** - * Get badge for the tab, uses `route.badge` by default. - */ - getBadge?: (props: { route: Route }) => boolean | number | string | undefined; - /** - * Get label text for the tab, uses `route.title` by default. Use `renderLabel` to replace label component. - */ - getLabelText?: (props: { route: Route }) => string | undefined; - /** - * Get lazy for the current screen. Uses true by default. - */ - getLazy?: (props: { route: Route }) => boolean | undefined; - /** - * Get the id to locate this tab button in tests, uses `route.testID` by default. - */ - getTestID?: (props: { route: Route }) => string | undefined; - /** - * Function to execute on tab press. It receives the route for the pressed tab, useful for things like scroll to top. - */ - onTabPress?: (props: { route: Route } & TabPressEvent) => void; - /** - * Function to execute on tab long press. It receives the route for the pressed tab, useful for things like custom action when longed pressed. - */ - onTabLongPress?: (props: { route: Route } & TabPressEvent) => void; - /** - * Custom color for icon and label in the active tab. - */ - activeColor?: string; - /** - * Custom color for icon and label in the inactive tab. - */ - inactiveColor?: string; - /** - * Whether animation is enabled for scenes transitions in `shifting` mode. - * By default, the scenes cross-fade during tab change when `shifting` is enabled. - * Specify `sceneAnimationEnabled` as `false` to disable the animation. - */ - sceneAnimationEnabled?: boolean; - /** - * The scene animation effect. Specify `'shifting'` for a different effect. - * By default, 'opacity' will be used. - */ - sceneAnimationType?: 'opacity' | 'shifting'; - /** - * The scene animation Easing. - */ - sceneAnimationEasing?: EasingFunction | undefined; - /** - * Whether the bottom navigation bar is hidden when keyboard is shown. - * On Android, this works best when [`windowSoftInputMode`](https://developer.android.com/guide/topics/manifest/activity-element#wsoft) is set to `adjustResize`. - */ - keyboardHidesNavigationBar?: boolean; - /** - * Safe area insets for the tab bar. This can be used to avoid elements like the navigation bar on Android and bottom safe area on iOS. - * The bottom insets for iOS is added by default. You can override the behavior with this option. - */ - safeAreaInsets?: { - top?: number; - right?: number; - bottom?: number; - left?: number; - }; - /** - * Style for the bottom navigation bar. You can pass a custom background color here: - * - * ```js - * barStyle={{ backgroundColor: '#694fad' }} - * ``` - */ - barStyle?: Animated.WithAnimatedValue>; - /** - * Specifies the largest possible scale a label font can reach. - */ - labelMaxFontSizeMultiplier?: number; - style?: StyleProp; - activeIndicatorStyle?: StyleProp; - /** - * @optional - */ - theme?: ThemeProp; - /** - * TestID used for testing purposes - */ - testID?: string; - /** - * testID for the underlying `BottomNavigation.Bar`. - */ - barTestID?: string; -}; - -const FAR_FAR_AWAY = Platform.OS === 'web' ? 0 : 9999; - -const SceneComponent = React.memo(({ component, ...rest }: any) => - React.createElement(component, rest) -); - -/** - * BottomNavigation provides quick navigation between top-level views of an app with a bottom navigation bar. - * It is primarily designed for use on mobile. If you want to use the navigation bar only see [`BottomNavigation.Bar`](BottomNavigationBar). - * - * ## Usage - * ```js - * import * as React from 'react'; - * import { BottomNavigation, Text } from 'react-native-paper'; - * - * const MusicRoute = () => Music; - * - * const AlbumsRoute = () => Albums; - * - * const RecentsRoute = () => Recents; - * - * const NotificationsRoute = () => Notifications; - * - * const MyComponent = () => { - * const [index, setIndex] = React.useState(0); - * const [routes] = React.useState([ - * { key: 'music', title: 'Favorites', focusedIcon: 'heart', unfocusedIcon: 'heart-outline'}, - * { key: 'albums', title: 'Albums', focusedIcon: 'album' }, - * { key: 'recents', title: 'Recents', focusedIcon: 'history' }, - * { key: 'notifications', title: 'Notifications', focusedIcon: 'bell', unfocusedIcon: 'bell-outline' }, - * ]); - * - * const renderScene = BottomNavigation.SceneMap({ - * music: MusicRoute, - * albums: AlbumsRoute, - * recents: RecentsRoute, - * notifications: NotificationsRoute, - * }); - * - * return ( - * - * ); - * }; - * - * export default MyComponent; - * ``` - */ -const BottomNavigation = ({ - navigationState, - renderScene, - renderIcon, - renderLabel, - renderTouchable, - getLabelText, - getBadge, - getAccessibilityLabel, - getTestID, - activeColor, - inactiveColor, - keyboardHidesNavigationBar = Platform.OS === 'android', - barStyle, - labeled = true, - style, - activeIndicatorStyle, - sceneAnimationEnabled = false, - sceneAnimationType = 'opacity', - sceneAnimationEasing, - onTabPress, - onTabLongPress, - onIndexChange, - shifting: shiftingProp, - safeAreaInsets, - labelMaxFontSizeMultiplier = 1, - compact: compactProp, - testID, - barTestID, - theme: themeOverrides, - getLazy = ({ route }: { route: Route }) => route.lazy, -}: Props) => { - const theme = useInternalTheme(themeOverrides); - const getDuration = useMotionDuration(); - const compact = compactProp ?? false; - let shifting = shiftingProp ?? false; - - if (shifting && navigationState.routes.length < 2) { - shifting = false; - console.warn( - 'BottomNavigation needs at least 2 tabs to run shifting animation' - ); - } - - const focusedKey = navigationState.routes[navigationState.index].key; - - /** - * Active state of individual tab item positions: - * -1 if they're before the active tab, 0 if they're active, 1 if they're after the active tab - */ - const tabsPositionAnims = useAnimatedValueArray( - navigationState.routes.map((_, i) => - i === navigationState.index ? 0 : i >= navigationState.index ? 1 : -1 - ) - ); - - /** - * The top offset for each tab item to position it offscreen. - * Placing items offscreen helps to save memory usage for inactive screens with removeClippedSubviews. - * We use animated values for this to prevent unnecessary re-renders. - */ - const offsetsAnims = useAnimatedValueArray( - navigationState.routes.map( - // offscreen === 1, normal === 0 - (_, i) => (i === navigationState.index ? 0 : 1) - ) - ); - - /** - * List of loaded tabs, tabs will be loaded when navigated to. - */ - const [loaded, setLoaded] = React.useState([focusedKey]); - - if (!loaded.includes(focusedKey)) { - // Set the current tab to be loaded if it was not loaded before - setLoaded((loaded) => [...loaded, focusedKey]); - } - - const animateToIndex = React.useCallback( - (index: number) => { - Animated.parallel([ - ...navigationState.routes.map((_, i) => - Animated.timing(tabsPositionAnims[i], { - toValue: i === index ? 0 : i >= index ? 1 : -1, - duration: getDuration(150), - useNativeDriver: true, - easing: sceneAnimationEasing, - }) - ), - ]).start(({ finished }) => { - if (finished) { - // Position all inactive screens offscreen to save memory usage - // Only do it when animation has finished to avoid glitches mid-transition if switching fast - offsetsAnims.forEach((offset, i) => { - if (i === index) { - offset.setValue(0); - } else { - offset.setValue(1); - } - }); - } - }); - }, - [ - navigationState.routes, - offsetsAnims, - getDuration, - tabsPositionAnims, - sceneAnimationEasing, - ] - ); - - React.useEffect(() => { - // Workaround for native animated bug in react-native@^0.57 - // Context: https://github.com/callstack/react-native-paper/pull/637 - animateToIndex(navigationState.index); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - const prevNavigationState = React.useRef | undefined>( - undefined - ); - - React.useEffect(() => { - // Reset offsets of previous and current tabs before animation - offsetsAnims.forEach((offset, i) => { - if ( - i === navigationState.index || - i === prevNavigationState.current?.index - ) { - offset.setValue(0); - } - }); - - animateToIndex(navigationState.index); - }, [navigationState.index, animateToIndex, offsetsAnims]); - - const handleTabPress = useLatestCallback( - (event: { route: Route } & TabPressEvent) => { - onTabPress?.(event); - - if (event.defaultPrevented) { - return; - } - - const index = navigationState.routes.findIndex( - (route) => event.route.key === route.key - ); - - if (index !== navigationState.index) { - prevNavigationState.current = navigationState; - onIndexChange(index); - } - } - ); - - const jumpTo = useLatestCallback((key: string) => { - const index = navigationState.routes.findIndex( - (route) => route.key === key - ); - - prevNavigationState.current = navigationState; - onIndexChange(index); - }); - - const { routes } = navigationState; - const { colors } = theme; - - return ( - - - {routes.map((route, index) => { - if (getLazy({ route }) !== false && !loaded.includes(route.key)) { - // Don't render a screen if we've never navigated to it - return null; - } - - const focused = navigationState.index === index; - const previouslyFocused = - prevNavigationState.current?.index === index; - const countAlphaOffscreen = - sceneAnimationEnabled && (focused || previouslyFocused); - const renderToHardwareTextureAndroid = - sceneAnimationEnabled && focused; - - const opacity = sceneAnimationEnabled - ? tabsPositionAnims[index].interpolate({ - inputRange: [-1, 0, 1], - outputRange: [0, 1, 0], - }) - : focused - ? 1 - : 0; - - const offsetTarget = focused ? 0 : FAR_FAR_AWAY; - - const top = sceneAnimationEnabled - ? offsetsAnims[index].interpolate({ - inputRange: [0, 1], - outputRange: [0, offsetTarget], - }) - : offsetTarget; - - const left = - sceneAnimationType === 'shifting' - ? tabsPositionAnims[index].interpolate({ - inputRange: [-1, 0, 1], - outputRange: [-50, 0, 50], - }) - : 0; - - const zIndex = focused ? 1 : 0; - - return ( - - - {renderScene({ route, jumpTo })} - - - ); - })} - - - - ); -}; - -/** - * Function which takes a map of route keys to components. - * Pure components are used to minimize re-rendering of the pages. - * This drastically improves the animation performance. - */ -BottomNavigation.SceneMap = (scenes: { - [key: string]: React.ComponentType<{ - route: Route; - jumpTo: (key: string) => void; - }>; -}) => { - return ({ - route, - jumpTo, - }: { - route: Route; - jumpTo: (key: string) => void; - }) => ( - - ); -}; - -// @component ./BottomNavigationBar.tsx -BottomNavigation.Bar = BottomNavigationBar; - -export default BottomNavigation; - -const styles = StyleSheet.create({ - container: { - flex: 1, - overflow: 'hidden', - }, - content: { - flex: 1, - }, -}); diff --git a/src/components/BottomNavigation/BottomNavigationBar.tsx b/src/components/BottomNavigation/BottomNavigationBar.tsx deleted file mode 100644 index e2ba52677c..0000000000 --- a/src/components/BottomNavigation/BottomNavigationBar.tsx +++ /dev/null @@ -1,868 +0,0 @@ -import * as React from 'react'; -// eslint-disable-next-line no-restricted-imports -- TODO: migrate BottomNavigation to Reanimated. -import { Animated, Platform, StyleSheet, View } from 'react-native'; -import type { - ColorValue, - EasingFunction, - StyleProp, - ViewStyle, -} from 'react-native'; - -import { useSafeAreaInsets } from 'react-native-safe-area-context'; - -import { - getActiveTintColor, - getInactiveTintColor, - getLabelColor, -} from './utils'; -import { useInternalTheme } from '../../core/theming'; -import { useMotionDuration } from '../../theme/accessibility/ReduceMotionContext'; -import type { ThemeProp } from '../../theme/types'; -import useAnimatedValue from '../../utils/useAnimatedValue'; -import useAnimatedValueArray from '../../utils/useAnimatedValueArray'; -import useIsKeyboardShown from '../../utils/useIsKeyboardShown'; -import useLayout from '../../utils/useLayout'; -import Badge from '../Badge'; -import Icon from '../Icon'; -import type { IconSource } from '../Icon'; -import { Pressable } from '../TouchableRipple/Pressable'; -import TouchableRipple from '../TouchableRipple/TouchableRipple'; -import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple'; -import Text from '../Typography/Text'; - -type BaseRoute = { - key: string; - title?: string; - focusedIcon?: IconSource; - unfocusedIcon?: IconSource; - badge?: string | number | boolean; - /** - * Accessibility label for the tab. This is read by the screen reader when the user focuses the tab. - */ - 'aria-label'?: string; - testID?: string; - lazy?: boolean; -}; - -type NavigationState = { - index: number; - routes: Route[]; -}; - -type TabPressEvent = { - defaultPrevented: boolean; - preventDefault(): void; -}; - -type TouchableProps = TouchableRippleProps & { - key: string; - route: Route; - children: React.ReactNode; - borderless?: boolean; - centered?: boolean; - rippleColor?: ColorValue; -}; - -export type Props = { - /** - * Whether the shifting style is used, the active tab icon shifts up to show the label and the inactive tabs won't have a label. - * - * By default, this is `false` with theme version 3 and `true` when you have more than 3 tabs. - * Pass `shifting={false}` to explicitly disable this animation, or `shifting={true}` to always use this animation. - * Note that you need at least 2 tabs be able to run this animation. - */ - shifting?: boolean; - /** - * Whether to show labels in tabs. When `false`, only icons will be displayed. - */ - labeled?: boolean; - /** - * Whether tabs should be spread across the entire width. - */ - compact?: boolean; - /** - * State for the bottom navigation. The state should contain the following properties: - * - * - `index`: a number representing the index of the active route in the `routes` array - * - `routes`: an array containing a list of route objects used for rendering the tabs - * - * Each route object should contain the following properties: - * - * - `key`: a unique key to identify the route (required) - * - `title`: title of the route to use as the tab label - * - `focusedIcon`: icon to use as the focused tab icon, can be a string, an image source or a react component @renamed Renamed from 'icon' to 'focusedIcon' in v5.x - * - `unfocusedIcon`: icon to use as the unfocused tab icon, can be a string, an image source or a react component @supported Available in v5.x with theme version 3 - * - `badge`: badge to show on the tab icon, can be `true` to show a dot, `string` or `number` to show text. - * - `aria-label`: accessibility label for the tab button - * - `testID`: test id for the tab button - * - * Example: - * - * ```js - * { - * index: 1, - * routes: [ - * { key: 'music', title: 'Favorites', focusedIcon: 'heart', unfocusedIcon: 'heart-outline'}, - * { key: 'albums', title: 'Albums', focusedIcon: 'album' }, - * { key: 'recents', title: 'Recents', focusedIcon: 'history' }, - * { key: 'notifications', title: 'Notifications', focusedIcon: 'bell', unfocusedIcon: 'bell-outline' }, - * ] - * } - * ``` - * - * `BottomNavigation.Bar` is a controlled component, which means the `index` needs to be updated via the `onTabPress` callback. - */ - navigationState: NavigationState; - /** - * Callback which returns a React Element to be used as tab icon. - */ - renderIcon?: (props: { - route: Route; - focused: boolean; - color: ColorValue; - }) => React.ReactNode; - /** - * Callback which React Element to be used as tab label. - */ - renderLabel?: (props: { - route: Route; - focused: boolean; - color: ColorValue; - }) => React.ReactNode; - /** - * Callback which returns a React element to be used as the touchable for the tab item. - * Renders a `TouchableRipple` on Android and `Pressable` on iOS. - */ - renderTouchable?: (props: TouchableProps) => React.ReactNode; - /** - * Get accessibility label for the tab button. This is read by the screen reader when the user taps the tab. - * Uses `route['aria-label']` by default. - */ - getAccessibilityLabel?: (props: { route: Route }) => string | undefined; - /** - * Get badge for the tab, uses `route.badge` by default. - */ - getBadge?: (props: { route: Route }) => boolean | number | string | undefined; - /** - * Get label text for the tab, uses `route.title` by default. Use `renderLabel` to replace label component. - */ - getLabelText?: (props: { route: Route }) => string | undefined; - /** - * Get the id to locate this tab button in tests, uses `route.testID` by default. - */ - getTestID?: (props: { route: Route }) => string | undefined; - /** - * Function to execute on tab press. It receives the route for the pressed tab. Use this to update the navigation state. - */ - onTabPress: (props: { route: Route } & TabPressEvent) => void; - /** - * Function to execute on tab long press. It receives the route for the pressed tab - */ - onTabLongPress?: (props: { route: Route } & TabPressEvent) => void; - /** - * Custom color for icon and label in the active tab. - */ - activeColor?: string; - /** - * Custom color for icon and label in the inactive tab. - */ - inactiveColor?: string; - /** - * The scene animation Easing. - */ - animationEasing?: EasingFunction | undefined; - /** - * Whether the bottom navigation bar is hidden when keyboard is shown. - * On Android, this works best when [`windowSoftInputMode`](https://developer.android.com/guide/topics/manifest/activity-element#wsoft) is set to `adjustResize`. - */ - keyboardHidesNavigationBar?: boolean; - /** - * Safe area insets for the tab bar. This can be used to avoid elements like the navigation bar on Android and bottom safe area on iOS. - * The bottom insets for iOS is added by default. You can override the behavior with this option. - */ - safeAreaInsets?: { - top?: number; - right?: number; - bottom?: number; - left?: number; - }; - /** - * Specifies the largest possible scale a label font can reach. - */ - labelMaxFontSizeMultiplier?: number; - style?: Animated.WithAnimatedValue>; - activeIndicatorStyle?: StyleProp; - /** - * @optional - */ - theme?: ThemeProp; - /** - * TestID used for testing purposes - */ - testID?: string; -}; - -const MIN_TAB_WIDTH = 96; -const MAX_TAB_WIDTH = 168; -const BAR_HEIGHT = 56; -const OUTLINE_WIDTH = 64; - -const Touchable = ({ - route: _0, - style, - children, - borderless, - centered, - rippleColor, - focusRing, - theme, - ...rest -}: TouchableProps) => - TouchableRipple.supported ? ( - - {children} - - ) : ( - - {children} - - ); - -/** - * A navigation bar which can easily be integrated with [React Navigation's Bottom Tabs Navigator](https://reactnavigation.org/docs/bottom-tab-navigator/). - * - * ## Usage - * ### without React Navigation - * ```js - * import React from 'react'; - * import { useState } from 'react'; - * import { View } from 'react-native'; - * import { BottomNavigation, Text, Provider } from 'react-native-paper'; - * import MaterialCommunityIcons from '@react-native-vector-icons/material-design-icons'; - * - * function HomeScreen() { - * return ( - * - * Home! - * - * ); - * } - * - * function SettingsScreen() { - * return ( - * - * Settings! - * - * ); - * } - * - * export default function MyComponent() { - * const [index, setIndex] = useState(0); - * - * const routes = [ - * { key: 'home', title: 'Home', icon: 'home' }, - * { key: 'settings', title: 'Settings', icon: 'cog' }, - * ]; - - * const renderScene = ({ route }) => { - * switch (route.key) { - * case 'home': - * return ; - * case 'settings': - * return ; - * default: - * return null; - * } - * }; - * - * return ( - * - * {renderScene({ route: routes[index] })} - * { - * const newIndex = routes.findIndex((r) => r.key === route.key); - * if (newIndex !== -1) { - * setIndex(newIndex); - * } - * }} - * renderIcon={({ route, color }) => ( - * - * )} - * getLabelText={({ route }) => route.title} - * /> - * - * ); - * } - * ``` - */ -const BottomNavigationBar = ({ - navigationState, - renderIcon, - renderLabel, - renderTouchable = ({ key, ...props }: TouchableProps) => ( - - ), - getLabelText = ({ route }: { route: Route }) => route.title, - getBadge = ({ route }: { route: Route }) => route.badge, - getAccessibilityLabel = ({ route }: { route: Route }) => route['aria-label'], - getTestID = ({ route }: { route: Route }) => route.testID, - activeColor, - inactiveColor, - keyboardHidesNavigationBar = Platform.OS === 'android', - style, - activeIndicatorStyle, - labeled = true, - animationEasing, - onTabPress, - onTabLongPress, - shifting: shiftingProp, - safeAreaInsets, - labelMaxFontSizeMultiplier = 1, - compact: compactProp, - testID, - theme: themeOverrides, -}: Props) => { - const theme = useInternalTheme(themeOverrides); - const { colors } = theme; - const { bottom, left, right } = useSafeAreaInsets(); - const getDuration = useMotionDuration(); - const compact = compactProp ?? false; - let shifting = shiftingProp ?? false; - - if (shifting && navigationState.routes.length < 2) { - shifting = false; - console.warn( - 'BottomNavigation.Bar needs at least 2 tabs to run shifting animation' - ); - } - - /** - * Visibility of the navigation bar, visible state is 1 and invisible is 0. - */ - const visibleAnim = useAnimatedValue(1); - - /** - * Active state of individual tab items, active state is 1 and inactive state is 0. - */ - const tabsAnims = useAnimatedValueArray( - navigationState.routes.map( - // focused === 1, unfocused === 0 - (_, i) => (i === navigationState.index ? 1 : 0) - ) - ); - - /** - * Layout of the navigation bar. - */ - const [layout, onLayout] = useLayout(); - - /** - * Track whether the keyboard is visible to show and hide the navigation bar. - */ - const [keyboardVisible, setKeyboardVisible] = React.useState(false); - - const handleKeyboardShow = React.useCallback(() => { - setKeyboardVisible(true); - Animated.timing(visibleAnim, { - toValue: 0, - duration: getDuration(150), - useNativeDriver: true, - }).start(); - }, [getDuration, visibleAnim]); - - const handleKeyboardHide = React.useCallback(() => { - Animated.timing(visibleAnim, { - toValue: 1, - duration: getDuration(100), - useNativeDriver: true, - }).start(() => { - setKeyboardVisible(false); - }); - }, [getDuration, visibleAnim]); - - const animateToIndex = React.useCallback( - (index: number) => { - Animated.parallel( - navigationState.routes.map((_, i) => - Animated.timing(tabsAnims[i], { - toValue: i === index ? 1 : 0, - duration: getDuration(150), - useNativeDriver: true, - easing: animationEasing, - }) - ) - ).start(() => { - // Workaround a bug in native animations where this is reset after first animation - tabsAnims.map((tab, i) => tab.setValue(i === index ? 1 : 0)); - }); - }, - [getDuration, navigationState.routes, tabsAnims, animationEasing] - ); - - React.useEffect(() => { - // Workaround for native animated bug in react-native@^0.57 - // Context: https://github.com/callstack/react-native-paper/pull/637 - animateToIndex(navigationState.index); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - useIsKeyboardShown({ - onShow: handleKeyboardShow, - onHide: handleKeyboardHide, - }); - - React.useEffect(() => { - animateToIndex(navigationState.index); - }, [navigationState.index, animateToIndex]); - - const eventForIndex = (index: number) => { - const event = { - route: navigationState.routes[index], - defaultPrevented: false, - preventDefault: () => { - event.defaultPrevented = true; - }, - }; - - return event; - }; - - const { routes } = navigationState; - - const activeTintColor = getActiveTintColor({ - activeColor, - theme, - }); - - const inactiveTintColor = getInactiveTintColor({ - inactiveColor, - theme, - }); - - const maxTabWidth = routes.length > 3 ? MIN_TAB_WIDTH : MAX_TAB_WIDTH; - const maxTabBarWidth = maxTabWidth * routes.length; - - const insets = { - left: safeAreaInsets?.left ?? left, - right: safeAreaInsets?.right ?? right, - bottom: safeAreaInsets?.bottom ?? bottom, - }; - - const pointerEvents = layout.measured - ? keyboardHidesNavigationBar && keyboardVisible - ? 'none' - : 'auto' - : 'none'; - - return ( - - ); -}; - -BottomNavigationBar.displayName = 'BottomNavigation.Bar'; - -export default BottomNavigationBar; - -const styles = StyleSheet.create({ - bar: { - left: 0, - right: 0, - bottom: 0, - }, - barContent: { - alignItems: 'center', - overflow: 'hidden', - }, - items: { - flexDirection: 'row', - ...(Platform.OS === 'web' - ? { - width: '100%', - } - : null), - }, - item: { - flex: 1, - // Top padding is 6 and bottom padding is 10 - // The extra 4dp bottom padding is offset by label's height - paddingVertical: 6, - // `borderless` doesn't clip on web, so a label wider than its tab would - // spill into the neighbouring tabs. - ...(Platform.OS === 'web' ? { overflow: 'hidden' } : null), - }, - v3Item: { - paddingVertical: 0, - }, - iconContainer: { - height: 24, - width: 24, - marginTop: 2, - marginHorizontal: 12, - alignSelf: 'center', - }, - v3IconContainer: { - height: 32, - width: 32, - marginBottom: 4, - marginTop: 0, - justifyContent: 'center', - }, - iconWrapper: { - ...StyleSheet.absoluteFill, - alignItems: 'center', - }, - v3IconWrapper: { - top: 4, - }, - labelContainer: { - height: 16, - paddingBottom: 2, - }, - labelWrapper: { - ...StyleSheet.absoluteFill, - }, - // eslint-disable-next-line react-native/no-color-literals - label: { - fontSize: 12, - height: BAR_HEIGHT, - textAlign: 'center', - backgroundColor: 'transparent', - ...(Platform.OS === 'web' - ? { - whiteSpace: 'nowrap', - alignSelf: 'center', - } - : null), - }, - badgeContainer: { - position: 'absolute', - left: 0, - }, - v3TouchableContainer: { - paddingTop: 12, - paddingBottom: 16, - }, - v3NoLabelContainer: { - height: 80, - justifyContent: 'center', - alignItems: 'center', - }, - outline: { - width: OUTLINE_WIDTH, - height: OUTLINE_WIDTH / 2, - borderRadius: OUTLINE_WIDTH / 4, - alignSelf: 'center', - }, -}); diff --git a/src/components/BottomNavigation/BottomNavigationRouteScreen.tsx b/src/components/BottomNavigation/BottomNavigationRouteScreen.tsx deleted file mode 100644 index affffc6793..0000000000 --- a/src/components/BottomNavigation/BottomNavigationRouteScreen.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import React from 'react'; -import type { ReactNode } from 'react'; -// eslint-disable-next-line no-restricted-imports -- TODO: migrate BottomNavigation to Reanimated. -import { Animated, Platform, View } from 'react-native'; -import type { ViewProps } from 'react-native'; - -interface Props extends ViewProps { - visibility?: 0 | 1 | Animated.AnimatedInterpolation; - index: number; -} - -class BottomNavigationRouteScreen extends React.Component { - render(): ReactNode { - const { style, index, children, visibility, ...rest } = this.props; - - // On Web, the unfocused tab screens can still be clicked since they are transparent, but still there - // Hiding them with `display: none` makes sure that they won't receive clicks - // We only set it on Web since on native, react-native-pager-view's breaks due to layout changing - const display = - Platform.OS === 'web' ? (visibility === 0 ? 'none' : 'flex') : undefined; - - return ( - - {children} - - ); - } -} - -export default Animated.createAnimatedComponent(BottomNavigationRouteScreen); diff --git a/src/components/BottomNavigation/utils.ts b/src/components/BottomNavigation/utils.ts deleted file mode 100644 index 3e772cd141..0000000000 --- a/src/components/BottomNavigation/utils.ts +++ /dev/null @@ -1,53 +0,0 @@ -import type { ColorValue } from 'react-native'; - -import type { InternalTheme } from '../../theme/types'; - -export const getActiveTintColor = ({ - activeColor, - theme, -}: { - activeColor: ColorValue | undefined; - theme: InternalTheme; -}): ColorValue => { - if (activeColor != null) { - return activeColor; - } - - return theme.colors.onSecondaryContainer; -}; - -export const getInactiveTintColor = ({ - inactiveColor, - theme, -}: { - inactiveColor: ColorValue | undefined; - theme: InternalTheme; -}): ColorValue => { - if (inactiveColor != null) { - return inactiveColor; - } - - return theme.colors.onSurfaceVariant; -}; - -export const getLabelColor = ({ - tintColor, - hasColor, - focused, - theme, -}: { - tintColor: ColorValue; - hasColor: boolean; - focused: boolean; - theme: InternalTheme; -}): ColorValue => { - const { colors } = theme; - if (hasColor) { - return tintColor; - } - - if (focused) { - return colors.onSurface; - } - return colors.onSurfaceVariant; -}; diff --git a/src/components/NavigationBar/NavigationBar.tsx b/src/components/NavigationBar/NavigationBar.tsx new file mode 100644 index 0000000000..56ae6f4c3b --- /dev/null +++ b/src/components/NavigationBar/NavigationBar.tsx @@ -0,0 +1,1001 @@ +import * as React from 'react'; +import { Platform, StyleSheet, View } from 'react-native'; +import type { + ColorValue, + NativeSyntheticEvent, + StyleProp, + TextStyle, + ViewStyle, +} from 'react-native'; + +import Animated, { + cubicBezier, + type CSSStyle, + Easing, + ReduceMotion, + useAnimatedStyle, + useSharedValue, + withTiming, +} from 'react-native-reanimated'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; +import { scheduleOnRN } from 'react-native-worklets'; + +import { + BAR_HEIGHT, + colorRoles, + ICON_LABEL_GAP, + ICON_SIZE, + HORIZONTAL_INDICATOR_HEIGHT, + INDICATOR_HEIGHT, + INDICATOR_WIDTH, + MAX_TAB_WIDTH, + MIN_TAB_WIDTH, + NO_LABEL_BAR_HEIGHT, +} from './tokens'; +import { + getActiveTintColor, + getInactiveTintColor, + getLabelColor, + getStateLayerColor, +} from './utils'; +import { useLocale } from '../../core/locale'; +import { useInternalTheme } from '../../core/theming'; +import { useReduceMotion } from '../../theme/accessibility/ReduceMotionContext'; +import { cornerFull } from '../../theme/tokens/sys/shape'; +import type { Theme, ThemeProp } from '../../theme/types'; +import { isKeyboardFocusEvent } from '../../utils/isKeyboardFocusEvent'; +import useIsKeyboardShown from '../../utils/useIsKeyboardShown'; +import useLayout from '../../utils/useLayout'; +import { useSpaceKeyPress } from '../../utils/useSpaceKeyPress'; +import Badge from '../Badge'; +import Icon from '../Icon'; +import type { IconSource } from '../Icon'; +import { Pressable } from '../TouchableRipple/Pressable'; +import TouchableRipple from '../TouchableRipple/TouchableRipple'; +import type { Props as TouchableRippleProps } from '../TouchableRipple/TouchableRipple'; +import Text from '../Typography/Text'; + +export type BaseRoute = { + key: string; + title?: string; + focusedIcon?: IconSource; + unfocusedIcon?: IconSource; + badge?: string | number | boolean; + 'aria-label'?: string; + testID?: string; +}; + +type NavigationState = { + index: number; + routes: Route[]; +}; + +type TouchableProps = TouchableRippleProps & { + key: string; + route: Route; + children: React.ReactNode; + borderless?: boolean; + centered?: boolean; + rippleColor?: ColorValue; +}; + +// React Native 0.87+ exports `KeyDownEvent`, but its legacy types, the default +// before 0.87, do not, so type only what is read. +type TabKeyEvent = NativeSyntheticEvent<{ key: string; repeat?: boolean }>; + +export type Props = { + /** + * Whether to show labels in tabs. When `false`, only icons will be displayed. + */ + labeled?: boolean; + /** + * The item layout variant of the flexible navigation bar. + * + * - `stacked` (default): the icon sits above the label. + * - `horizontal`: the icon sits beside the label and the active indicator + * hugs both. Recommended for medium-width windows (e.g. foldables and + * tablets). Has no effect when `labeled` is `false`. + */ + variant?: 'stacked' | 'horizontal'; + /** + * Whether to limit the width of the tab row and center it in the bar. Each + * tab then gets at most 168dp, or 96dp when there are more than 3 tabs. When + * `false`, the tabs fill the full width of the bar. + */ + compact?: boolean; + /** + * State for the navigation bar. The state contains the following properties: + * + * - `index`: a number representing the index of the active route in the `routes` array + * - `routes`: an array containing a list of route objects used for rendering the tabs + * + * Each route object should contain the following properties: + * + * - `key`: a unique key to identify the route (required) + * - `title`: title of the route to use as the tab label + * - `focusedIcon`: icon to use as the focused tab icon, can be a string, an image source or a react component + * - `unfocusedIcon`: icon to use as the unfocused tab icon, can be a string, an image source or a react component. Falls back to `focusedIcon`. + * - `badge`: badge to show on the tab icon, can be `true` to show a dot, `string` or `number` to show text. + * - `aria-label`: accessibility label for the tab button. Replaces the default label, which is the label text and the badge. + * - `testID`: test id for the tab button + * + * Example: + * + * ```js + * { + * index: 1, + * routes: [ + * { key: 'music', title: 'Favorites', focusedIcon: 'heart', unfocusedIcon: 'heart-outline'}, + * { key: 'albums', title: 'Albums', focusedIcon: 'album' }, + * { key: 'recents', title: 'Recents', focusedIcon: 'history' }, + * { key: 'notifications', title: 'Notifications', focusedIcon: 'bell', unfocusedIcon: 'bell-outline' }, + * ] + * } + * ``` + * + * `NavigationBar` is a controlled component, which means the `index` needs to be updated via the `onTabPress` callback. + */ + navigationState: NavigationState; + /** + * Callback which returns a React Element to be used as tab icon. + */ + renderIcon?: (props: { + route: Route; + focused: boolean; + color: ColorValue; + }) => React.ReactNode; + /** + * Callback which React Element to be used as tab label. + */ + renderLabel?: (props: { + route: Route; + focused: boolean; + color: ColorValue; + }) => React.ReactNode; + /** + * Callback which returns a React element to be used as the touchable for the tab item. + * Renders a `TouchableRipple` on Android and web, and a `Pressable` on iOS. + * + * A custom touchable must pass on the `onPress`, `onLongPress`, + * `onPressIn`, `onPressOut`, `onHoverIn`, `onHoverOut`, `onFocus`, + * `onBlur`, `onKeyDown` and `onKeyUp` handlers and the `tabIndex` it + * receives. Without them, the state layers and the keyboard support on web + * stop working. + */ + renderTouchable?: (props: TouchableProps) => React.ReactNode; + /** + * Get accessibility label for the tab button. This is read by the screen reader when the user taps the tab. + * Uses `route['aria-label']`. Without it, the label is the label text + * (`getLabelText`) and, for a text or number badge, the badge + * (for example "Inbox, 3"), so icon-only tabs keep an accessible name. + */ + getAccessibilityLabel?: (props: { route: Route }) => string | undefined; + /** + * Get badge for the tab, uses `route.badge` by default. + */ + getBadge?: (props: { route: Route }) => boolean | number | string | undefined; + /** + * Get label text for the tab, uses `route.title` by default. Use `renderLabel` to replace label component. + */ + getLabelText?: (props: { route: Route }) => string | undefined; + /** + * Get the id to locate this tab button in tests, uses `route.testID` by default. + */ + getTestID?: (props: { route: Route }) => string | undefined; + /** + * Function to execute on tab press. It receives the route for the pressed tab. Use this to update the navigation state. + */ + onTabPress: (props: { route: Route }) => void; + /** + * Function to execute on tab long press. It receives the route for the pressed tab + */ + onTabLongPress?: (props: { route: Route }) => void; + /** + * Custom color for icon and label in the active tab. + */ + activeColor?: string; + /** + * Custom color for icon and label in the inactive tab. + */ + inactiveColor?: string; + /** + * Whether the navigation bar is hidden when keyboard is shown. + * On Android, this works best when [`windowSoftInputMode`](https://developer.android.com/guide/topics/manifest/activity-element#wsoft) is set to `adjustResize`. + */ + keyboardHidesNavigationBar?: boolean; + /** + * Safe area insets for the tab bar. This can be used to avoid elements like the navigation bar on Android and bottom safe area on iOS. + * The bottom insets for iOS is added by default. You can override the behavior with this option. + */ + safeAreaInsets?: { + top?: number; + right?: number; + bottom?: number; + left?: number; + }; + /** + * Specifies the largest possible scale a label font can reach. + */ + labelMaxFontSizeMultiplier?: number; + /** + * Style for the bar container. The default background color is + * `surfaceContainer`. Set `backgroundColor` here to change it. + */ + style?: StyleProp; + /** + * Style for the active indicator, the pill behind the icon of the active + * tab (or behind the icon and the label in the `horizontal` variant). + */ + activeIndicatorStyle?: StyleProp; + /** + * @optional + */ + theme?: ThemeProp; + /** + * TestID used for testing purposes + */ + testID?: string; +}; + +const Touchable = ({ + route: _0, + style, + children, + borderless, + centered, + rippleColor, + focusRing, + theme, + ...rest +}: TouchableProps) => + TouchableRipple.supported ? ( + + {children} + + ) : ( + + {children} + + ); + +type ItemProps = { + route: Route; + focused: boolean; + labeled: boolean; + variant: 'stacked' | 'horizontal'; + activeTintColor: ColorValue; + inactiveTintColor: ColorValue; + activeColor?: string; + inactiveColor?: string; + renderIcon?: Props['renderIcon']; + renderLabel?: Props['renderLabel']; + renderTouchable: NonNullable['renderTouchable']>; + getLabelText: NonNullable['getLabelText']>; + getBadge: NonNullable['getBadge']>; + getTestID: NonNullable['getTestID']>; + getAccessibilityLabel: NonNullable['getAccessibilityLabel']>; + onPress: () => void; + onLongPress?: () => void; + activeIndicatorStyle?: StyleProp; + labelMaxFontSizeMultiplier?: number; + theme: Theme; +}; + +const NavigationBarItem = ({ + route, + focused, + labeled, + variant, + activeTintColor, + inactiveTintColor, + activeColor, + inactiveColor, + renderIcon, + renderLabel, + renderTouchable, + getLabelText, + getBadge, + getTestID, + getAccessibilityLabel, + onPress, + onLongPress, + activeIndicatorStyle, + labelMaxFontSizeMultiplier = 1, + theme, +}: ItemProps) => { + const { colors } = theme; + const { direction } = useLocale(); + + const [hovered, setHovered] = React.useState(false); + const [keyboardFocused, setKeyboardFocused] = React.useState(false); + const [pressed, setPressed] = React.useState(false); + + const reduceMotion = useReduceMotion(); + + const indicatorTransition: CSSStyle = { + opacity: focused ? 1 : 0, + transitionDuration: reduceMotion ? 0 : theme.motion.duration.medium2, + transitionProperty: ['opacity', 'transform'], + transitionTimingFunction: cubicBezier(...theme.motion.easing.emphasized), + }; + + const stackedIndicatorStyle: CSSStyle = { + ...indicatorTransition, + transform: [{ scaleX: focused ? 1 : 0.5 }], + }; + + const horizontalIndicatorStyle: CSSStyle = { + ...indicatorTransition, + transform: [{ scale: focused ? 1 : 0.8 }], + }; + + const iconColor = focused ? activeTintColor : inactiveTintColor; + const labelColor = getLabelColor({ + tintColor: iconColor, + hasColor: Boolean(focused ? activeColor : inactiveColor), + focused, + theme, + }); + + const badge = getBadge({ route }); + const badgeStyle = { + top: typeof badge === 'boolean' ? 4 : 2, + right: + badge != null && typeof badge !== 'boolean' + ? String(badge).length * -2 + : 0, + }; + + const font = theme.fonts.labelMedium; + + const stateLayerColor = getStateLayerColor({ + theme, + pressed, + keyboardFocused, + hovered, + }); + + const handlePressIn = () => setPressed(true); + const handlePressOut = () => setPressed(false); + + // React Native Web presses only `button`s on Space, so the hook presses a + // tab on Space release, the same way Enter does. + const { keyHandlers: spaceKeyHandlers, onBlur: handleSpaceKeyBlur } = + useSpaceKeyPress({ + onPress, + onPressIn: handlePressIn, + onPressOut: handlePressOut, + }); + + // The tabs pattern moves focus between tabs with the arrow keys, Home and + // End. Only web gets these key events. Native focus systems move focus + // themselves. + const moveFocus = (event: TabKeyEvent) => { + const { currentTarget } = event; + + if ( + typeof HTMLElement === 'undefined' || + !(currentTarget instanceof HTMLElement) + ) + return; + + const tabs = + currentTarget.parentElement?.querySelectorAll( + '[role="tab"]' + ); + + if (!tabs || tabs.length === 0) return; + + const index = Array.prototype.indexOf.call(tabs, currentTarget); + const step = direction === 'rtl' ? -1 : 1; + let nextIndex: number | undefined; + + switch (event.nativeEvent.key) { + case 'ArrowRight': + nextIndex = (index + step + tabs.length) % tabs.length; + break; + case 'ArrowLeft': + nextIndex = (index - step + tabs.length) % tabs.length; + break; + case 'Home': + nextIndex = 0; + break; + case 'End': + nextIndex = tabs.length - 1; + break; + default: + return; + } + + if (nextIndex !== index) { + event.preventDefault(); + tabs[nextIndex]?.focus(); + } + }; + + const keyHandlers = + Platform.OS === 'web' + ? { + onKeyDown: (event: TabKeyEvent) => { + spaceKeyHandlers?.onKeyDown(event); + moveFocus(event); + }, + onKeyUp: spaceKeyHandlers?.onKeyUp, + } + : null; + + const itemTestID = getTestID({ route }); + + // The horizontal arrangement places the label beside the icon and only + // applies when labels are shown; otherwise it falls back to stacked icon-only. + const horizontal = variant === 'horizontal' && labeled; + + // Item pieces shared across both layouts. The active/inactive distinction is + // a plain color swap (no cross-fade), so a single icon and label suffice. + const iconSource = focused + ? route.focusedIcon + : (route.unfocusedIcon ?? route.focusedIcon); + + const icon = renderIcon ? ( + renderIcon({ route, focused, color: iconColor }) + ) : iconSource !== undefined ? ( + + ) : null; + + const tabBadge = ( + + {typeof badge === 'boolean' ? ( + + ) : ( + {badge} + )} + + ); + + const renderTabLabel = ( + labelStyle: StyleProp, + numberOfLines?: number + ) => + renderLabel ? ( + renderLabel({ route, focused, color: labelColor }) + ) : ( + + {getLabelText({ route })} + + ); + + // No `pointerEvents="none"` on the content wrappers. On Android it also stops + // hover events, so TalkBack explore by touch could not focus the tab. + const stackedContent = ( + + + + + + + {icon} + {tabBadge} + + {labeled ? ( + + {renderTabLabel(styles.label, 1)} + + ) : null} + + ); + + const horizontalContent = ( + + + + + {/* The same 32dp box as the stacked icon, so the badge sits at the + same place on the icon in both layouts. */} + + {icon} + {tabBadge} + + {renderTabLabel(styles.horizontalLabel, 1)} + + + ); + + return renderTouchable({ + key: route.key, + route, + borderless: true, + centered: true, + rippleColor: 'transparent', + // Tabs fill the bar edge to edge and the bar clips + // (`overflow: 'hidden'`), so an outward ring would lose its top and bottom + // and read as two vertical lines between tabs. + focusRing: 'inward', + theme, + onPress, + // Only with a handler: while `onLongPress` is set, a press longer than + // 500ms does not call `onPress`. + ...(onLongPress ? { onLongPress } : null), + onPressIn: handlePressIn, + onPressOut: handlePressOut, + onHoverIn: () => setHovered(true), + onHoverOut: () => setHovered(false), + onFocus: (event) => { + if (isKeyboardFocusEvent(event)) { + setKeyboardFocused(true); + } + }, + onBlur: (event) => { + handleSpaceKeyBlur(event); + setKeyboardFocused(false); + }, + ...keyHandlers, + testID: itemTestID, + 'aria-label': getAccessibilityLabel({ route }), + role: Platform.OS === 'ios' ? 'button' : 'tab', + 'aria-selected': focused, + // React Native Web gives every pressable `tabIndex={0}`. The tabs pattern + // has one Tab stop, the selected tab, and the arrow keys move focus. + tabIndex: Platform.OS === 'web' ? (focused ? 0 : -1) : undefined, + style: horizontal ? styles.horizontalTouchable : styles.item, + children: horizontal ? horizontalContent : stackedContent, + }); +}; + +/** + * The Material Design 3 flexible navigation bar. It can easily be integrated + * with [React Navigation's Bottom Tabs Navigator](https://reactnavigation.org/docs/bottom-tab-navigator/). + * + * Set the `variant` prop to `'horizontal'` to lay items out horizontally + * (icon beside label) in medium-width windows. + * + * ## Usage + * ### without React Navigation + * ```js + * import * as React from 'react'; + * import { View } from 'react-native'; + * import { NavigationBar, Text, Provider } from 'react-native-paper'; + * + * function HomeScreen() { + * return ( + * + * Home! + * + * ); + * } + * + * function SettingsScreen() { + * return ( + * + * Settings! + * + * ); + * } + * + * export default function MyComponent() { + * const [index, setIndex] = React.useState(0); + * + * const routes = [ + * { key: 'home', title: 'Home', focusedIcon: 'home' }, + * { key: 'settings', title: 'Settings', focusedIcon: 'cog' }, + * ]; + * + * const renderScene = ({ route }) => { + * switch (route.key) { + * case 'home': + * return ; + * case 'settings': + * return ; + * default: + * return null; + * } + * }; + * + * return ( + * + * {renderScene({ route: routes[index] })} + * { + * const newIndex = routes.findIndex((r) => r.key === route.key); + * if (newIndex !== -1) { + * setIndex(newIndex); + * } + * }} + * getLabelText={({ route }) => route.title} + * /> + * + * ); + * } + * ``` + */ +const NavigationBar = ({ + navigationState, + renderIcon, + renderLabel, + renderTouchable = ({ key, ...props }: TouchableProps) => ( + + ), + getLabelText = ({ route }: { route: Route }) => route.title, + getBadge = ({ route }: { route: Route }) => route.badge, + getAccessibilityLabel = ({ route }: { route: Route }) => { + if (route['aria-label'] !== undefined) return route['aria-label']; + + // The label replaces the text inside the tab, so the badge goes into it. + // A dot badge (`true`) has no text to read. + const label = getLabelText({ route }); + const badge = getBadge({ route }); + + if ( + (typeof badge !== 'string' && typeof badge !== 'number') || + badge === '' + ) + return label; + + return label ? `${label}, ${badge}` : String(badge); + }, + getTestID = ({ route }: { route: Route }) => route.testID, + activeColor, + inactiveColor, + keyboardHidesNavigationBar = Platform.OS === 'android', + style, + activeIndicatorStyle, + labeled = true, + variant = 'stacked', + onTabPress, + onTabLongPress, + safeAreaInsets, + labelMaxFontSizeMultiplier = 1, + compact: compactProp, + testID, + theme: themeOverrides, +}: Props) => { + const theme = useInternalTheme(themeOverrides); + const { colors, motion } = theme; + const { bottom, left, right } = useSafeAreaInsets(); + const compact = compactProp ?? false; + + const reduceMotion = useReduceMotion(); + const reanimatedReduceMotion = reduceMotion + ? ReduceMotion.Always + : ReduceMotion.Never; + + /** + * Visibility of the navigation bar, visible state is 1 and invisible is 0. + */ + const visible = useSharedValue(1); + + /** + * Layout of the navigation bar. + */ + const [layout, onLayout] = useLayout(); + + /** + * Track whether the keyboard is visible to show and hide the navigation bar. + */ + const [keyboardVisible, setKeyboardVisible] = React.useState(false); + + const handleKeyboardShow = React.useCallback(() => { + setKeyboardVisible(true); + visible.value = withTiming(0, { + // The bar slides out, so accelerate (exit). + duration: motion.duration.short3, + easing: Easing.bezier(...motion.easing.standardAccelerate), + reduceMotion: reanimatedReduceMotion, + }); + }, [motion, reanimatedReduceMotion, visible]); + + const handleKeyboardHide = React.useCallback(() => { + visible.value = withTiming( + 1, + { + // The bar slides back in, so decelerate (enter). + duration: motion.duration.short2, + easing: Easing.bezier(...motion.easing.standardDecelerate), + reduceMotion: reanimatedReduceMotion, + }, + (finished) => { + if (finished) { + scheduleOnRN(setKeyboardVisible, false); + } + } + ); + }, [motion, reanimatedReduceMotion, visible]); + + // Slide the bar down by its own height when the keyboard hides it. + const barAnimatedStyle = useAnimatedStyle(() => ({ + transform: [{ translateY: (1 - visible.value) * layout.height }], + })); + + useIsKeyboardShown({ + onShow: handleKeyboardShow, + onHide: handleKeyboardHide, + }); + + const eventForIndex = (index: number) => { + return { route: navigationState.routes[index] }; + }; + + const { routes } = navigationState; + + const activeTintColor = getActiveTintColor({ + activeColor, + theme, + }); + + const inactiveTintColor = getInactiveTintColor({ + inactiveColor, + theme, + }); + + // `horizontal` applies only when labels are shown. + const itemLayout = + variant === 'horizontal' && labeled ? 'horizontal' : 'stacked'; + + const maxTabWidth = routes.length > 3 ? MIN_TAB_WIDTH : MAX_TAB_WIDTH; + const maxTabBarWidth = maxTabWidth * routes.length; + + const insets = { + left: safeAreaInsets?.left ?? left, + right: safeAreaInsets?.right ?? right, + bottom: safeAreaInsets?.bottom ?? bottom, + }; + + return ( + + + + {routes.map((route, index) => { + const focused = navigationState.index === index; + + return ( + onTabPress(eventForIndex(index))} + onLongPress={ + onTabLongPress + ? () => onTabLongPress(eventForIndex(index)) + : undefined + } + activeIndicatorStyle={activeIndicatorStyle} + labelMaxFontSizeMultiplier={labelMaxFontSizeMultiplier} + theme={theme} + /> + ); + })} + + + + ); +}; + +NavigationBar.displayName = 'NavigationBar'; + +export default NavigationBar; + +const styles = StyleSheet.create({ + bar: { + left: 0, + right: 0, + bottom: 0, + }, + absolute: { + position: 'absolute', + }, + barContent: { + alignItems: 'center', + overflow: 'hidden', + }, + items: { + flexDirection: 'row', + ...(Platform.OS === 'web' + ? { + width: '100%', + } + : null), + }, + item: { + flex: 1, + paddingVertical: 0, + // `borderless` does not clip on web, so a label wider than its tab would + // spill into the neighboring tabs. + ...(Platform.OS === 'web' ? { overflow: 'hidden' } : null), + }, + horizontalTouchable: { + flexGrow: 0, + flexShrink: 1, + maxWidth: MAX_TAB_WIDTH, + paddingVertical: 0, + }, + // A 32dp square around the 24dp icon. The pill is wider and overflows it. + // The square is the anchor for the badge. + iconContainer: { + height: INDICATOR_HEIGHT, + width: INDICATOR_HEIGHT, + alignSelf: 'center', + justifyContent: 'center', + }, + iconContainerLabeled: { + marginBottom: ICON_LABEL_GAP, + }, + // The same square as `iconContainer`. The negative margins keep the 24dp + // icon width in the row, so the item padding stays 16dp. + horizontalIconContainer: { + height: INDICATOR_HEIGHT, + width: INDICATOR_HEIGHT, + marginHorizontal: (ICON_SIZE - INDICATOR_HEIGHT) / 2, + }, + iconWrapper: { + ...StyleSheet.absoluteFill, + top: 4, + alignItems: 'center', + }, + labelContainer: { + height: 16, + }, + // eslint-disable-next-line react-native/no-color-literals + label: { + fontSize: 12, + textAlign: 'center', + backgroundColor: 'transparent', + ...(Platform.OS === 'web' + ? { + whiteSpace: 'nowrap', + alignSelf: 'center', + } + : null), + }, + badgeContainer: { + position: 'absolute', + left: 0, + }, + stackedContainer: { + height: BAR_HEIGHT, + justifyContent: 'center', + }, + noLabelContainer: { + height: NO_LABEL_BAR_HEIGHT, + justifyContent: 'center', + alignItems: 'center', + }, + stackedIndicator: { + width: INDICATOR_WIDTH, + height: INDICATOR_HEIGHT, + borderRadius: cornerFull, + alignSelf: 'center', + }, + stateLayerWrapper: { + ...StyleSheet.absoluteFill, + alignItems: 'center', + justifyContent: 'center', + }, + stateLayer: { + width: INDICATOR_WIDTH, + height: INDICATOR_HEIGHT, + borderRadius: cornerFull, + overflow: 'hidden', + }, + horizontalContainer: { + height: BAR_HEIGHT, + justifyContent: 'center', + alignItems: 'center', + }, + horizontalItem: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'center', + height: HORIZONTAL_INDICATOR_HEIGHT, + paddingHorizontal: 16, + }, + horizontalIndicator: { + borderRadius: cornerFull, + overflow: 'hidden', + }, + horizontalLabel: { + flexShrink: 1, + marginStart: ICON_LABEL_GAP, + textAlign: 'center', + ...(Platform.OS === 'web' + ? { + whiteSpace: 'nowrap', + } + : null), + }, + horizontalItems: { + justifyContent: 'center', + }, +}); diff --git a/src/components/NavigationBar/index.tsx b/src/components/NavigationBar/index.tsx new file mode 100644 index 0000000000..3567b88e01 --- /dev/null +++ b/src/components/NavigationBar/index.tsx @@ -0,0 +1,2 @@ +export { default } from './NavigationBar'; +export type { Props, BaseRoute } from './NavigationBar'; diff --git a/src/components/NavigationBar/tokens.ts b/src/components/NavigationBar/tokens.ts new file mode 100644 index 0000000000..87a084de88 --- /dev/null +++ b/src/components/NavigationBar/tokens.ts @@ -0,0 +1,40 @@ +import type { ColorRole } from '../../theme/types'; + +/** + * Resolved M3 "flexible navigation bar" spec values. + * @see https://m3.material.io/components/navigation-bar/specs + */ + +// Container heights (dp). The flexible navigation bar is shorter than the +// original navigation bar (which was 80dp). +export const BAR_HEIGHT = 64; +export const NO_LABEL_BAR_HEIGHT = 64; + +// Stacked active indicator / state-layer pill (dp). +export const INDICATOR_WIDTH = 56; +export const INDICATOR_HEIGHT = 32; + +// Horizontal active indicator / state-layer pill (dp). Its width hugs content. +export const HORIZONTAL_INDICATOR_HEIGHT = 40; + +// Icon + spacing (dp). +export const ICON_SIZE = 24; +export const ICON_LABEL_GAP = 4; + +// Tab width clamps used by the `compact` layout (dp). +export const MIN_TAB_WIDTH = 96; +export const MAX_TAB_WIDTH = 168; + +/** + * Color roles per the M3 spec. `activeLabel` is `secondary` (changed from + * `onSurface` in Material 3 / Compose Material3 1.4.0). + */ +export const colorRoles = { + container: 'surfaceContainer', + activeIcon: 'onSecondaryContainer', + activeIndicator: 'secondaryContainer', + activeLabel: 'secondary', + stateLayer: 'onSecondaryContainer', + inactiveIcon: 'onSurfaceVariant', + inactiveLabel: 'onSurfaceVariant', +} as const satisfies Record; diff --git a/src/components/NavigationBar/utils.ts b/src/components/NavigationBar/utils.ts new file mode 100644 index 0000000000..47dabe1a53 --- /dev/null +++ b/src/components/NavigationBar/utils.ts @@ -0,0 +1,82 @@ +import type { ColorValue } from 'react-native'; + +import { colorRoles } from './tokens'; +import type { InternalTheme, StateOpacityKey } from '../../theme/types'; +import { getStateLayer } from '../../theme/utils/state'; + +export const getActiveTintColor = ({ + activeColor, + theme, +}: { + activeColor: ColorValue | undefined; + theme: InternalTheme; +}): ColorValue => { + if (activeColor != null) { + return activeColor; + } + + return theme.colors[colorRoles.activeIcon]; +}; + +export const getInactiveTintColor = ({ + inactiveColor, + theme, +}: { + inactiveColor: ColorValue | undefined; + theme: InternalTheme; +}): ColorValue => { + if (inactiveColor != null) { + return inactiveColor; + } + + return theme.colors[colorRoles.inactiveIcon]; +}; + +export const getLabelColor = ({ + tintColor, + hasColor, + focused, + theme, +}: { + tintColor: ColorValue; + hasColor: boolean; + focused: boolean; + theme: InternalTheme; +}): ColorValue => { + const { colors } = theme; + if (hasColor) { + return tintColor; + } + + return colors[focused ? colorRoles.activeLabel : colorRoles.inactiveLabel]; +}; + +/** + * MD3 state layer for navigation bar item: 10% on press & focus, 8% on + * hover. Active & inactive items both use on-secondary-container role + */ +export const getStateLayerColor = ({ + theme, + pressed, + keyboardFocused, + hovered, +}: { + theme: InternalTheme; + pressed: boolean; + keyboardFocused: boolean; + hovered: boolean; +}): { backgroundColor: ColorValue; opacity: number } | null => { + const interactionsByPriority: [StateOpacityKey, boolean][] = [ + ['pressed', pressed], + ['focused', keyboardFocused], + ['hovered', hovered], + ]; + + const state = interactionsByPriority.find(([, isActive]) => isActive)?.[0]; + + if (!state) return null; + + const { color, opacity } = getStateLayer(theme, colorRoles.stateLayer, state); + + return { backgroundColor: color, opacity }; +}; diff --git a/src/components/__tests__/BottomNavigation.test.tsx b/src/components/__tests__/BottomNavigation.test.tsx deleted file mode 100644 index 7707b0b73b..0000000000 --- a/src/components/__tests__/BottomNavigation.test.tsx +++ /dev/null @@ -1,680 +0,0 @@ -/* eslint-disable no-restricted-imports -- TODO: remove after BottomNavigation migrates to Reanimated. */ -import { - Animated, - Easing, - Keyboard, - Platform, - StyleSheet, - Text, -} from 'react-native'; -/* eslint-enable no-restricted-imports */ -import type { KeyboardEvent } from 'react-native'; - -import { describe, expect, it, jest } from '@jest/globals'; -import { act, fireEvent, userEvent } from '@testing-library/react-native'; - -import { render, screen } from '../../test-utils'; -import { LightTheme } from '../../theme/schemes'; -import { Palette } from '../../theme/tokens'; -import BottomNavigation from '../BottomNavigation/BottomNavigation'; -import BottomNavigationRouteScreen from '../BottomNavigation/BottomNavigationRouteScreen'; -import { - getActiveTintColor, - getInactiveTintColor, - getLabelColor, -} from '../BottomNavigation/utils'; -import Icon from '../Icon'; - -const styles = StyleSheet.create({ - backgroundColor: { - backgroundColor: Palette.error60, - }, -}); - -const icons = ['magnify', 'camera', 'inbox', 'heart', 'shopping-music']; - -const createState = (index: number, length: number) => ({ - index, - routes: Array.from({ length }, (_, i) => ({ - key: `key-${i}`, - focusedIcon: icons[i], - unfocusedIcon: undefined, - title: `Route: ${i}`, - })), -}); - -const renderScene = ({ route }: { route: { title: string } }) => ( - {route.title} -); - -const getTab = (index: number) => - screen.getAllByRole(Platform.OS === 'ios' ? 'button' : 'tab')[index]; - -const layoutNavigationBar = async () => { - await fireEvent(screen.getByTestId('bottom-navigation-bar'), 'layout', { - nativeEvent: { - layout: { height: 56, width: 360 }, - }, - }); -}; - -it('renders shifting bottom navigation', async () => { - const tree = ( - await render( - - ) - ).toJSON(); - - expect(tree).toMatchSnapshot(); -}); - -it('renders bottom navigation with scene animation', async () => { - const tree = ( - await render( - - ) - ).toJSON(); - - expect(tree).toMatchSnapshot(); -}); - -// eslint-disable-next-line jest/no-disabled-tests -it.skip('sceneAnimationEnabled matches animation requirements', async () => { - const ease = Easing.ease; - - await render( - - ); - - // Simulate the button press - await userEvent.press(screen.getAllByRole('button')[1]); - - // Expect the calls to Animated.parallel - expect(Animated.parallel).toHaveBeenCalledTimes(2); - - // Expect the first call to Animated.parallel - expect(Animated.parallel).toHaveBeenCalledWith( - expect.arrayContaining([ - expect.objectContaining({ - // ripple - config: expect.objectContaining({ toValue: 1, duration: 400 }), - }), - ]) - ); - - // Expect the second call to Animated.parallel - expect(Animated.parallel).toHaveBeenCalledWith( - expect.arrayContaining([ - expect.objectContaining({ - // previous position anims, shifting to the left - config: expect.objectContaining({ - toValue: -1, - duration: 150, - easing: ease, - }), - }), - expect.objectContaining({ - // active page visibility - config: expect.objectContaining({ - toValue: 1, - duration: 150, - easing: ease, - }), - }), - expect.objectContaining({ - // next position anims, shifting to the right - config: expect.objectContaining({ - toValue: 1, - duration: 150, - easing: ease, - }), - }), - ]) - ); -}); - -it('calls onIndexChange', async () => { - const onIndexChange = jest.fn(); - await render( - - ); - - await layoutNavigationBar(); - - // pressing same index as active navigation state does not call onIndexChange - await userEvent.press(getTab(0)); - expect(onIndexChange).not.toHaveBeenCalled(); - - await userEvent.press(getTab(1)); - expect(onIndexChange).toHaveBeenCalledTimes(1); -}); - -it('calls onTabPress', async () => { - const onTabPress = jest.fn(); - const onIndexChange = jest.fn(); - - await render( - - ); - - await layoutNavigationBar(); - - await userEvent.press(getTab(1)); - expect(onTabPress).toHaveBeenCalled(); - expect(onTabPress).toHaveBeenCalledTimes(1); - expect(onTabPress).toHaveBeenLastCalledWith( - expect.objectContaining({ - route: expect.objectContaining({ - key: 'key-1', - }), - defaultPrevented: expect.any(Boolean), - preventDefault: expect.any(Function), - }) - ); -}); - -it('calls onTabLongPress', async () => { - const onTabLongPress = jest.fn(); - const onIndexChange = jest.fn(); - - await render( - - ); - - await layoutNavigationBar(); - - await userEvent.longPress(getTab(2)); - expect(onTabLongPress).toHaveBeenCalled(); - expect(onTabLongPress).toHaveBeenCalledTimes(1); - expect(onTabLongPress).toHaveBeenLastCalledWith( - expect.objectContaining({ - route: expect.objectContaining({ - key: 'key-2', - }), - defaultPrevented: expect.any(Boolean), - preventDefault: expect.any(Function), - }) - ); -}); - -it('renders non-shifting bottom navigation', async () => { - const tree = ( - await render( - - ) - ).toJSON(); - - expect(tree).toMatchSnapshot(); -}); - -it('does not crash when shifting is true and the number of tabs in the navigationState is less than 2', async () => { - jest.spyOn(console, 'warn').mockImplementation(() => {}); - - await render( - - ); - - expect(console.warn).toHaveBeenCalledWith( - 'BottomNavigation needs at least 2 tabs to run shifting animation' - ); - - jest.restoreAllMocks(); -}); - -it('renders custom icon and label in shifting bottom navigation', async () => { - const tree = ( - await render( - ( - - )} - renderLabel={({ route, color }) => ( - - {route.title} - - )} - /> - ) - ).toJSON(); - - expect(tree).toMatchSnapshot(); -}); - -it('renders custom icon and label in non-shifting bottom navigation', async () => { - const tree = ( - await render( - ( - - )} - renderLabel={({ route, color }) => ( - - {route.title} - - )} - /> - ) - ).toJSON(); - - expect(tree).toMatchSnapshot(); -}); - -it('renders custom icon and label with custom colors in shifting bottom navigation', async () => { - const tree = ( - await render( - - ) - ).toJSON(); - - expect(tree).toMatchSnapshot(); -}); - -it('renders custom icon and label with custom colors in non-shifting bottom navigation', async () => { - const tree = ( - await render( - - ) - ).toJSON(); - - expect(tree).toMatchSnapshot(); -}); - -it('hides labels in shifting bottom navigation', async () => { - const tree = ( - await render( - - ) - ).toJSON(); - - expect(tree).toMatchSnapshot(); -}); - -it('hides labels in non-shifting bottom navigation', async () => { - const tree = ( - await render( - - ) - ).toJSON(); - - expect(tree).toMatchSnapshot(); -}); - -it('should have appropriate display style according to the visibility on web', async () => { - const originalPlatform = Platform.OS; - Platform.OS = 'web'; - - const { rerender } = await render( - - ); - - const wrapper = screen.getByTestId('RouteScreen: 0'); - - expect(wrapper).toHaveStyle({ display: 'flex' }); - - await rerender(); - expect(wrapper).toHaveStyle({ display: 'none' }); - - Platform.OS = originalPlatform; -}); - -it('should have labelMaxFontSizeMultiplier passed to label', async () => { - const labelMaxFontSizeMultiplier = 2; - await render( - - ); - - const label = screen.getAllByText('Route: 0').find( - // eslint-disable-next-line no-restricted-syntax -- TODO: replace TestInstance props access with a user-visible assertion. - (item) => item.props.maxFontSizeMultiplier === labelMaxFontSizeMultiplier - ); - - expect(label).toBeTruthy(); -}); - -it('renders custom background color passed to barStyle property', async () => { - const { toJSON } = await render( - - ); - - expect(toJSON()).toMatchSnapshot(); -}); - -it('uses the rendered bar height when hiding it for the keyboard', async () => { - let handleKeyboardShow: ((event: KeyboardEvent) => void) | undefined; - const addKeyboardListener = Keyboard.addListener.bind(Keyboard); - const keyboardListenerSpy = jest - .spyOn(Keyboard, 'addListener') - .mockImplementation((event, listener) => { - if (event.endsWith('Show')) { - handleKeyboardShow = listener; - } - - return addKeyboardListener(event, listener); - }); - - await render( - - ); - - const navigation = screen.getByTestId('bottom-navigation'); - - await fireEvent(navigation, 'layout', { - nativeEvent: { - layout: { height: 72, width: 360 }, - }, - }); - - await act(() => { - handleKeyboardShow?.({ - duration: 0, - easing: 'keyboard', - endCoordinates: { - screenX: 0, - screenY: 500, - width: 360, - height: 300, - }, - }); - jest.runAllTimers(); - }); - - expect(navigation).toHaveStyle({ - height: 96, - position: 'absolute', - transform: [{ translateY: 72 }], - }); - - keyboardListenerSpy.mockRestore(); -}); - -it('renders a single tab', async () => { - await render( - - ); - - expect(screen.getByTestId('bottom-navigation')).toBeOnTheScreen(); -}); - -it('renders bottom navigation with getLazy', async () => { - const view = await render( - route.key === 'key-2'} - /> - ); - - expect(view).toMatchSnapshot(); - - expect(screen.queryByTestId('RouteScreen: 2')).not.toBeOnTheScreen(); -}); - -it('applies maxTabBarWidth styling if compact prop is truthy', async () => { - const { toJSON } = await render( - route.key === 'key-2'} - shifting={false} - compact - /> - ); - - expect(toJSON()).toMatchSnapshot(); -}); - -it('does not apply maxTabBarWidth styling if compact prop is falsy', async () => { - const { toJSON } = await render( - route.key === 'key-2'} - shifting={false} - compact={false} - /> - ); - - expect(toJSON()).toMatchSnapshot(); -}); - -describe('getActiveTintColor', () => { - it.each` - activeColor | expected - ${'#FBF7DB'} | ${'#FBF7DB'} - ${undefined} | ${Palette.secondary10} - `( - 'returns $expected when activeColor: $activeColor', - ({ activeColor, expected }) => { - const result = getActiveTintColor({ activeColor, theme: LightTheme }); - expect(result).toBe(expected); - } - ); -}); - -describe('getInactiveTintColor', () => { - it.each` - inactiveColor | expected - ${'#853D4B'} | ${'#853D4B'} - ${undefined} | ${Palette.neutralVariant30} - `( - 'returns $expected when inactiveColor: $inactiveColor', - ({ inactiveColor, expected }) => { - const result = getInactiveTintColor({ - inactiveColor, - theme: LightTheme, - }); - expect(result).toBe(expected); - } - ); -}); - -describe('getLabelColor', () => { - it.each([ - { tintColor: '#FBF7DB', focused: true, expected: '#FBF7DB' }, - { tintColor: '#853D4B', focused: true, expected: '#853D4B' }, - { tintColor: undefined, focused: true, expected: Palette.neutral10 }, - { - tintColor: undefined, - focused: false, - expected: Palette.neutralVariant30, - }, - ])( - 'returns $expected when tintColor: $tintColor, focused: $focused', - ({ tintColor, focused, expected }) => { - const result = getLabelColor({ - tintColor: tintColor ?? '', - hasColor: Boolean(tintColor), - focused, - theme: LightTheme, - }); - expect(result).toBe(expected); - } - ); -}); - -it('supports animated styles in bar', async () => { - const value = new Animated.Value(1); - await render( - - ); - - expect(screen.getByTestId('bottom-navigation')).toHaveStyle({ - transform: [{ scale: 1 }], - }); - - Animated.timing(value, { - toValue: 1.5, - useNativeDriver: false, - duration: 200, - }).start(); - - await act(() => { - jest.advanceTimersByTime(200); - }); - - expect(screen.getByTestId('bottom-navigation')).toHaveStyle({ - transform: [{ scale: 1.5 }], - }); -}); - -it("allows customizing Route's type via generics", async () => { - type CustomRoute = { - key: string; - customPropertyName: string; - }; - - type CustomState = { - index: number; - routes: CustomRoute[]; - }; - - const state: CustomState = { - index: 0, - routes: [ - { key: 'a', customPropertyName: 'First' }, - { key: 'b', customPropertyName: 'Second' }, - ], - }; - - const tree = ( - await render( - route.customPropertyName} - renderScene={({ route }) => {route.customPropertyName}} - /> - ) - ).toJSON(); - - expect(tree).toMatchSnapshot(); -}); diff --git a/src/components/__tests__/NavigationBar.test.tsx b/src/components/__tests__/NavigationBar.test.tsx new file mode 100644 index 0000000000..e24cde2fac --- /dev/null +++ b/src/components/__tests__/NavigationBar.test.tsx @@ -0,0 +1,696 @@ +import type { ComponentProps } from 'react'; +import { Platform } from 'react-native'; + +import { afterEach, describe, expect, it, jest } from '@jest/globals'; +import { fireEvent, userEvent } from '@testing-library/react-native'; + +import { LocaleProvider } from '../../core/locale'; +import { render, screen } from '../../test-utils'; +import { LightTheme } from '../../theme/schemes'; +import { Palette } from '../../theme/tokens'; +import NavigationBar from '../NavigationBar/NavigationBar'; +import { getStateLayerColor } from '../NavigationBar/utils'; + +const icons = ['magnify', 'camera', 'inbox', 'heart', 'shopping-music']; + +// `role="tab"` is only used outside iOS, where it is reported as a button. +const tabRole = Platform.OS === 'ios' ? 'button' : 'tab'; + +// The bar ignores pointer events until it has been laid out for the first +// time, so the interaction tests lay it out before touching a tab. +const renderLaidOutBar = async ( + props: ComponentProps +) => { + const utils = await render( + + ); + + await fireEvent(screen.getByTestId('navigation-bar'), 'layout', { + nativeEvent: { layout: { x: 0, y: 700, width: 393, height: 88 } }, + }); + + return utils; +}; + +const createState = (index: number, length: number) => ({ + index, + routes: Array.from({ length }, (_, i) => ({ + key: `key-${i}`, + focusedIcon: icons[i], + unfocusedIcon: undefined, + title: `Route: ${i}`, + })), +}); + +it('renders tab labels when labeled', async () => { + await render( + + ); + + expect(screen.getByText('Alpha')).toBeOnTheScreen(); + expect(screen.getByText('Beta')).toBeOnTheScreen(); +}); + +it('keeps stacked labels on one line', async () => { + await render( + + ); + + expect(screen.getByText('Route: 0')).toHaveProp('numberOfLines', 1); + expect(screen.getByText('Route: 0')).toHaveProp('ellipsizeMode', 'tail'); +}); + +it('exposes the tabs pattern through accessibility roles', async () => { + await render( + + ); + + // The `tablist` container is a group, not an accessibility element (making it + // one would swallow the tabs on iOS), so it is not queryable. Its role is + // covered by the structural snapshots. + expect(screen.getAllByRole(tabRole)).toHaveLength(2); + expect( + screen.getByRole(tabRole, { name: 'Alpha destination' }) + ).toBeSelected(); + expect(screen.getByRole(tabRole, { name: 'Beta' })).not.toBeSelected(); +}); + +it('names icon-only tabs with the label text', async () => { + await render( + + ); + + // No label is rendered, but the accessible name still identifies the tab. + expect(screen.queryByText('Alpha')).toBeNull(); + expect(screen.getByRole(tabRole, { name: 'Alpha' })).toBeTruthy(); + expect(screen.getByRole(tabRole, { name: 'Beta' })).toBeTruthy(); +}); + +it('keeps an explicit aria-label over the label text', async () => { + await render( + + ); + + expect(screen.getByRole(tabRole, { name: 'Alpha destination' })).toBeTruthy(); +}); + +it('calls onTabPress with the pressed route', async () => { + const navigationState = createState(0, 3); + const onTabPress = jest.fn(); + + const user = userEvent.setup(); + await renderLaidOutBar({ navigationState, onTabPress }); + + await user.press(screen.getByRole(tabRole, { name: 'Route: 1' })); + + expect(onTabPress).toHaveBeenCalledTimes(1); + expect(onTabPress).toHaveBeenCalledWith({ route: navigationState.routes[1] }); +}); + +it('calls onTabLongPress with the pressed route', async () => { + const navigationState = createState(0, 3); + const onTabLongPress = jest.fn(); + + const user = userEvent.setup(); + await renderLaidOutBar({ + navigationState, + onTabPress: jest.fn(), + onTabLongPress, + }); + + await user.longPress(screen.getByRole(tabRole, { name: 'Route: 1' })); + + expect(onTabLongPress).toHaveBeenCalledTimes(1); + expect(onTabLongPress).toHaveBeenCalledWith({ + route: navigationState.routes[1], + }); +}); + +it('calls onTabPress after a long press when there is no onTabLongPress', async () => { + const navigationState = createState(0, 3); + const onTabPress = jest.fn(); + + const user = userEvent.setup(); + await renderLaidOutBar({ navigationState, onTabPress }); + + await user.longPress(screen.getByRole(tabRole, { name: 'Route: 1' })); + + expect(onTabPress).toHaveBeenCalledTimes(1); + expect(onTabPress).toHaveBeenCalledWith({ route: navigationState.routes[1] }); +}); + +it('renders the horizontal (flexible) variant', async () => { + const tree = ( + await render( + + ) + ).toJSON(); + + expect(tree).toMatchSnapshot(); +}); + +it('truncates a long label instead of growing past the tab in the horizontal variant', async () => { + await render( + + ); + + expect(screen.getByText('Route: 0')).toHaveProp('numberOfLines', 1); + expect(screen.getByText('Route: 0')).toHaveProp('ellipsizeMode', 'tail'); +}); + +it('gives the tabs equal widths again after a change from horizontal to stacked', async () => { + const navigationState = createState(0, 3); + + await render( + + ); + + for (const tab of screen.getAllByRole(tabRole)) { + expect(tab).not.toHaveStyle({ flex: 1 }); + } + + await screen.rerender( + + ); + + for (const tab of screen.getAllByRole(tabRole)) { + expect(tab).toHaveStyle({ flex: 1 }); + } +}); + +it('falls back to icon-only when horizontal is combined with labeled=false', async () => { + await render( + + ); + + // `horizontal` is a no-op without labels, so no label text is rendered. + expect(screen.queryByText('Route: 0')).toBeNull(); + expect(screen.queryByText('Route: 1')).toBeNull(); +}); + +it('renders the MD3 state layer for hover, focus and press', async () => { + await render( + + ); + + const tab = () => screen.getByTestId('tab').toJSON(); + + expect(tab()).toMatchSnapshot('idle'); + + await fireEvent(screen.getByTestId('tab'), 'hoverIn'); + expect(tab()).toMatchSnapshot('hovered'); + await fireEvent(screen.getByTestId('tab'), 'hoverOut'); + + await fireEvent(screen.getByTestId('tab'), 'focus'); + expect(tab()).toMatchSnapshot('focused'); + await fireEvent(screen.getByTestId('tab'), 'blur'); + + await fireEvent(screen.getByTestId('tab'), 'pressIn'); + expect(tab()).toMatchSnapshot('pressed'); + await fireEvent(screen.getByTestId('tab'), 'pressOut'); + + expect(tab()).toMatchSnapshot('released'); +}); + +it('only shows the focus state layer for keyboard focus on web', async () => { + const platform = Platform.OS; + Platform.OS = 'web'; + + try { + await render( + + ); + + const tab = () => screen.getByTestId('tab').toJSON(); + + await fireEvent(screen.getByTestId('tab'), 'hoverIn'); + await fireEvent(screen.getByTestId('tab'), 'focus', { + currentTarget: { matches: () => false }, + }); + // Focus from a pointer keeps the hover layer only. + expect(tab()).toMatchSnapshot('pointer-focus'); + + await fireEvent(screen.getByTestId('tab'), 'focus', { + currentTarget: { matches: () => true }, + }); + // Keyboard focus swaps it for the focus layer. + expect(tab()).toMatchSnapshot('keyboard-focus'); + } finally { + await screen.unmount(); + Platform.OS = platform; + } +}); + +it('applies the default container color to the bar', async () => { + await render( + + ); + + expect(screen.getByTestId('navigation-bar')).toHaveStyle({ + backgroundColor: LightTheme.colors.surfaceContainer, + }); +}); + +it('lets the consumer style override the bar', async () => { + await render( + + ); + + // Everything lands on the bar itself, so no layout key can end up on an + // inner wrapper. + expect(screen.getByTestId('navigation-bar')).toHaveStyle({ + position: 'absolute', + top: 12, + flex: 1, + backgroundColor: Palette.error40, + }); +}); + +it('colors the focused tab label with secondary and others with onSurfaceVariant', async () => { + await render( + + ); + + expect(screen.getByText('Alpha')).toHaveStyle({ + color: LightTheme.colors.secondary, + }); + expect(screen.getByText('Beta')).toHaveStyle({ + color: LightTheme.colors.onSurfaceVariant, + }); +}); + +it('colors the labels with activeColor and inactiveColor', async () => { + await render( + + ); + + expect(screen.getByText('Alpha')).toHaveStyle({ color: '#FBF7DB' }); + expect(screen.getByText('Beta')).toHaveStyle({ color: '#853D4B' }); +}); + +it.each([ + { + colors: {}, + active: LightTheme.colors.onSecondaryContainer, + inactive: LightTheme.colors.onSurfaceVariant, + }, + { + colors: { activeColor: '#FBF7DB', inactiveColor: '#853D4B' }, + active: '#FBF7DB', + inactive: '#853D4B', + }, +])( + 'passes the icon colors to renderIcon with $colors', + async ({ colors, active, inactive }) => { + const renderIcon = jest.fn(() => null); + + await render( + + ); + + expect(renderIcon).toHaveBeenCalledWith( + expect.objectContaining({ focused: true, color: active }) + ); + expect(renderIcon).toHaveBeenCalledWith( + expect.objectContaining({ focused: false, color: inactive }) + ); + } +); + +it('renders a badge for routes that define one', async () => { + await render( + + ); + + expect(screen.getByText('3')).toBeOnTheScreen(); + expect(screen.getByRole(tabRole, { name: 'Alpha, 3' })).toBeSelected(); + expect(screen.getByRole(tabRole, { name: 'Beta' })).not.toBeSelected(); +}); + +it('leaves a dot badge out of the accessible name', async () => { + await render( + + ); + + expect(screen.getByRole(tabRole, { name: 'Alpha' })).toBeOnTheScreen(); +}); + +it('names an icon-only tab with its badge', async () => { + await render( + + ); + + expect(screen.getByRole(tabRole, { name: 'Inbox, 99+' })).toBeOnTheScreen(); +}); + +describe('on web', () => { + // A stand-in for the DOM tab elements that React Native Web renders. + class FakeTab { + focus = jest.fn(); + parentElement: { querySelectorAll: () => FakeTab[] }; + + constructor(siblings: FakeTab[]) { + // eslint-disable-next-line testing-library/no-node-access -- The fake stands in for the DOM element that the bar reads its sibling tabs from. + this.parentElement = { querySelectorAll: () => siblings }; + } + } + + const key = (name: string, currentTarget?: FakeTab, repeat = false) => ({ + nativeEvent: { key: name, repeat }, + currentTarget, + preventDefault: jest.fn(), + }); + + const createTabs = () => { + const tabs: FakeTab[] = []; + tabs.push(new FakeTab(tabs), new FakeTab(tabs), new FakeTab(tabs)); + return tabs; + }; + + const setUpWeb = () => { + jest.replaceProperty(Platform, 'OS', 'web'); + Object.defineProperty(globalThis, 'HTMLElement', { + configurable: true, + value: FakeTab, + }); + }; + + afterEach(() => { + jest.restoreAllMocks(); + Reflect.deleteProperty(globalThis, 'HTMLElement'); + }); + + it('makes only the selected tab a Tab stop', async () => { + setUpWeb(); + await render( + + ); + + const [first, selected, last] = screen.getAllByRole('tab'); + + expect(first).toHaveProp('tabIndex', -1); + expect(selected).toHaveProp('tabIndex', 0); + expect(last).toHaveProp('tabIndex', -1); + }); + + it('presses a tab once on Space release, even when Space is held', async () => { + setUpWeb(); + const navigationState = createState(0, 3); + const onTabPress = jest.fn(); + await render( + + ); + const tab = screen.getByRole('tab', { name: 'Route: 1' }); + const down = key(' '); + + await fireEvent(tab, 'keyDown', down); + await fireEvent(tab, 'keyDown', key(' ', undefined, true)); + await fireEvent(tab, 'keyDown', key(' ', undefined, true)); + + expect(down.preventDefault).toHaveBeenCalled(); + expect(onTabPress).not.toHaveBeenCalled(); + + await fireEvent(tab, 'keyUp', key(' ')); + + expect(onTabPress).toHaveBeenCalledTimes(1); + expect(onTabPress).toHaveBeenCalledWith({ + route: navigationState.routes[1], + }); + }); + + it.each([ + { direction: 'ltr', name: 'ArrowRight', from: 0, to: 1 }, + { direction: 'ltr', name: 'ArrowLeft', from: 0, to: 2 }, + { direction: 'ltr', name: 'ArrowRight', from: 2, to: 0 }, + { direction: 'rtl', name: 'ArrowRight', from: 1, to: 0 }, + { direction: 'rtl', name: 'ArrowLeft', from: 1, to: 2 }, + { direction: 'ltr', name: 'Home', from: 2, to: 0 }, + { direction: 'ltr', name: 'End', from: 0, to: 2 }, + ] as const)( + 'moves focus from tab $from to tab $to on $name in $direction', + async ({ direction, name, from, to }) => { + setUpWeb(); + const onTabPress = jest.fn(); + await render( + + + + ); + const tabs = createTabs(); + const event = key(name, tabs[from]); + + await fireEvent(screen.getAllByRole('tab')[from], 'keyDown', event); + + expect(tabs[to].focus).toHaveBeenCalledTimes(1); + expect(event.preventDefault).toHaveBeenCalled(); + expect(onTabPress).not.toHaveBeenCalled(); + } + ); + + it('leaves other keys to the browser', async () => { + setUpWeb(); + await render( + + ); + const tabs = createTabs(); + const event = key('ArrowDown', tabs[0]); + + await fireEvent(screen.getAllByRole('tab')[0], 'keyDown', event); + + expect(event.preventDefault).not.toHaveBeenCalled(); + for (const tab of tabs) { + expect(tab.focus).not.toHaveBeenCalled(); + } + }); +}); + +describe('getStateLayerColor', () => { + const stateLayerColor = LightTheme.colors.onSecondaryContainer; + + it.each([ + { + state: 'resting', + pressed: false, + keyboardFocused: false, + hovered: false, + opacity: null, + }, + { + state: 'pressed', + pressed: true, + keyboardFocused: false, + hovered: false, + opacity: 0.1, + }, + { + state: 'keyboard focused', + pressed: false, + keyboardFocused: true, + hovered: false, + opacity: 0.1, + }, + { + state: 'hovered', + pressed: false, + keyboardFocused: false, + hovered: true, + opacity: 0.08, + }, + { + state: 'pressed over hovered', + pressed: true, + keyboardFocused: false, + hovered: true, + opacity: 0.1, + }, + { + state: 'keyboard focused over hovered', + pressed: false, + keyboardFocused: true, + hovered: true, + opacity: 0.1, + }, + ])( + 'resolves the $state state layer with opacity $opacity', + ({ pressed, keyboardFocused, hovered, opacity }) => { + expect( + getStateLayerColor({ + theme: LightTheme, + pressed, + keyboardFocused, + hovered, + }) + ).toEqual( + opacity === null ? null : { backgroundColor: stateLayerColor, opacity } + ); + } + ); +}); diff --git a/src/components/__tests__/__snapshots__/BottomNavigation.test.tsx.snap b/src/components/__tests__/__snapshots__/BottomNavigation.test.tsx.snap deleted file mode 100644 index 538cf1ad1c..0000000000 --- a/src/components/__tests__/__snapshots__/BottomNavigation.test.tsx.snap +++ /dev/null @@ -1,17087 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`allows customizing Route's type via generics 1`] = ` - - - - - - First - - - - - - - - - - - - - - - - - - - - - First - - - - - First - - - - - - - - - - - - - - - - - - Second - - - - - Second - - - - - - - - - -`; - -exports[`applies maxTabBarWidth styling if compact prop is truthy 1`] = ` - - - - - - Route: 0 - - - - - - - Route: 1 - - - - - - - Route: 3 - - - - - - - Route: 4 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - Route: 0 - - - - - Route: 0 - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - Route: 1 - - - - - Route: 1 - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - Route: 2 - - - - - Route: 2 - - - - - - - - - - - heart - - - - - heart - - - - - - - - - - Route: 3 - - - - - Route: 3 - - - - - - - - - - - shopping-music - - - - - shopping-music - - - - - - - - - - Route: 4 - - - - - Route: 4 - - - - - - - - - -`; - -exports[`does not apply maxTabBarWidth styling if compact prop is falsy 1`] = ` - - - - - - Route: 0 - - - - - - - Route: 1 - - - - - - - Route: 3 - - - - - - - Route: 4 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - Route: 0 - - - - - Route: 0 - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - Route: 1 - - - - - Route: 1 - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - Route: 2 - - - - - Route: 2 - - - - - - - - - - - heart - - - - - heart - - - - - - - - - - Route: 3 - - - - - Route: 3 - - - - - - - - - - - shopping-music - - - - - shopping-music - - - - - - - - - - Route: 4 - - - - - Route: 4 - - - - - - - - - -`; - -exports[`hides labels in non-shifting bottom navigation 1`] = ` - - - - - - Route: 0 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - - - -`; - -exports[`hides labels in shifting bottom navigation 1`] = ` - - - - - - Route: 0 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - - - -`; - -exports[`renders bottom navigation with getLazy 1`] = ` - - - - - - Route: 0 - - - - - - - Route: 1 - - - - - - - Route: 3 - - - - - - - Route: 4 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - Route: 0 - - - - - Route: 0 - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - Route: 1 - - - - - Route: 1 - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - Route: 2 - - - - - Route: 2 - - - - - - - - - - - heart - - - - - heart - - - - - - - - - - Route: 3 - - - - - Route: 3 - - - - - - - - - - - shopping-music - - - - - shopping-music - - - - - - - - - - Route: 4 - - - - - Route: 4 - - - - - - - - - -`; - -exports[`renders bottom navigation with scene animation 1`] = ` - - - - - - Route: 0 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - Route: 0 - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - Route: 1 - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - Route: 2 - - - - - - - - - - - heart - - - - - heart - - - - - - - - - - Route: 3 - - - - - - - - - - - shopping-music - - - - - shopping-music - - - - - - - - - - Route: 4 - - - - - - - - - -`; - -exports[`renders custom background color passed to barStyle property 1`] = ` - - - - - - Route: 0 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - Route: 0 - - - - - Route: 0 - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - Route: 1 - - - - - Route: 1 - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - Route: 2 - - - - - Route: 2 - - - - - - - - - -`; - -exports[`renders custom icon and label in non-shifting bottom navigation 1`] = ` - - - - - - Route: 0 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - Route: 0 - - - - - Route: 0 - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - Route: 1 - - - - - Route: 1 - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - Route: 2 - - - - - Route: 2 - - - - - - - - - -`; - -exports[`renders custom icon and label in shifting bottom navigation 1`] = ` - - - - - - Route: 0 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - Route: 0 - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - Route: 1 - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - Route: 2 - - - - - - - - - - - heart - - - - - heart - - - - - - - - - - Route: 3 - - - - - - - - - - - shopping-music - - - - - shopping-music - - - - - - - - - - Route: 4 - - - - - - - - - -`; - -exports[`renders custom icon and label with custom colors in non-shifting bottom navigation 1`] = ` - - - - - - Route: 0 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - Route: 0 - - - - - Route: 0 - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - Route: 1 - - - - - Route: 1 - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - Route: 2 - - - - - Route: 2 - - - - - - - - - -`; - -exports[`renders custom icon and label with custom colors in shifting bottom navigation 1`] = ` - - - - - - Route: 0 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - Route: 0 - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - Route: 1 - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - Route: 2 - - - - - - - - - -`; - -exports[`renders non-shifting bottom navigation 1`] = ` - - - - - - Route: 0 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - Route: 0 - - - - - Route: 0 - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - Route: 1 - - - - - Route: 1 - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - Route: 2 - - - - - Route: 2 - - - - - - - - - -`; - -exports[`renders shifting bottom navigation 1`] = ` - - - - - - Route: 0 - - - - - - - - - - - - - - magnify - - - - - magnify - - - - - - - - - - Route: 0 - - - - - - - - - - - camera - - - - - camera - - - - - - - - - - Route: 1 - - - - - - - - - - - inbox - - - - - inbox - - - - - - - - - - Route: 2 - - - - - - - - - - - heart - - - - - heart - - - - - - - - - - Route: 3 - - - - - - - - - - - shopping-music - - - - - shopping-music - - - - - - - - - - Route: 4 - - - - - - - - - -`; diff --git a/src/components/__tests__/__snapshots__/NavigationBar.test.tsx.snap b/src/components/__tests__/__snapshots__/NavigationBar.test.tsx.snap new file mode 100644 index 0000000000..3c13274fbe --- /dev/null +++ b/src/components/__tests__/__snapshots__/NavigationBar.test.tsx.snap @@ -0,0 +1,2624 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`only shows the focus state layer for keyboard focus on web: keyboard-focus 1`] = ` + + + + + + + + + + camera + + + + + + + + + Route: 1 + + + + +`; + +exports[`only shows the focus state layer for keyboard focus on web: pointer-focus 1`] = ` + + + + + + + + + + camera + + + + + + + + + Route: 1 + + + + +`; + +exports[`renders the MD3 state layer for hover, focus and press: focused 1`] = ` + + + + + + + + + + camera + + + + + + + + + Route: 1 + + + + +`; + +exports[`renders the MD3 state layer for hover, focus and press: hovered 1`] = ` + + + + + + + + + + camera + + + + + + + + + Route: 1 + + + + +`; + +exports[`renders the MD3 state layer for hover, focus and press: idle 1`] = ` + + + + + + + + + + camera + + + + + + + + + Route: 1 + + + + +`; + +exports[`renders the MD3 state layer for hover, focus and press: pressed 1`] = ` + + + + + + + + + + camera + + + + + + + + + Route: 1 + + + + +`; + +exports[`renders the MD3 state layer for hover, focus and press: released 1`] = ` + + + + + + + + + + camera + + + + + + + + + Route: 1 + + + + +`; + +exports[`renders the horizontal (flexible) variant 1`] = ` + + + + + + + + + + + + magnify + + + + + + + + Route: 0 + + + + + + + + + + + + + camera + + + + + + + + Route: 1 + + + + + + + + + + + + + inbox + + + + + + + + Route: 2 + + + + + + + +`; diff --git a/src/components/__tests__/focusRingWiring.test.tsx b/src/components/__tests__/focusRingWiring.test.tsx index 1f9122d5bd..c7f63ce8f7 100644 --- a/src/components/__tests__/focusRingWiring.test.tsx +++ b/src/components/__tests__/focusRingWiring.test.tsx @@ -23,7 +23,6 @@ import Appbar from '../Appbar/Appbar'; import AppbarAction from '../Appbar/AppbarAction'; import AppbarBackAction from '../Appbar/AppbarBackAction'; import AppbarContent from '../Appbar/AppbarContent'; -import BottomNavigation from '../BottomNavigation/BottomNavigation'; import Button from '../Button/Button'; import Card from '../Card/Card'; import CheckboxItem from '../Checkbox/CheckboxItem'; @@ -39,6 +38,7 @@ import IconButton from '../IconButton/IconButton'; import ListAccordion from '../List/ListAccordion'; import ListItem from '../List/ListItem'; import MenuItem from '../Menu/MenuItem'; +import NavigationBar from '../NavigationBar/NavigationBar'; import RadioButtonItem from '../RadioButton/RadioButtonItem'; import SegmentedButtons from '../SegmentedButtons/SegmentedButtons'; import Snackbar from '../Snackbar'; @@ -150,9 +150,9 @@ describe('focus ring wiring', () => { // The bar clips (`overflow: 'hidden'`) and tabs fill it edge to edge, so an // outward ring loses its top and bottom. Rendered through a custom // `renderTouchable` so the test runs the ring path on every platform. - it('BottomNavigation.Bar rings its tabs inward', async () => { + it('NavigationBar rings its tabs inward', async () => { await render( - { , ], [ - 'BottomNavigation.Bar', - new Animated.Value(initialValue)); - - return current; -} diff --git a/src/utils/useAnimatedValueArray.tsx b/src/utils/useAnimatedValueArray.tsx deleted file mode 100644 index b26ed88793..0000000000 --- a/src/utils/useAnimatedValueArray.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import * as React from 'react'; -// eslint-disable-next-line no-restricted-imports -- TODO: remove after BottomNavigation migrates to Reanimated. -import { Animated } from 'react-native'; - -export default function useAnimatedValueArray(initialValues: number[]) { - const refs = React.useRef([]); - - refs.current.length = initialValues.length; - initialValues.forEach((initialValue, i) => { - refs.current[i] = refs.current[i] ?? new Animated.Value(initialValue); - }); - - return refs.current; -} diff --git a/src/utils/useLazyRef.tsx b/src/utils/useLazyRef.tsx deleted file mode 100644 index 5ef6aac27d..0000000000 --- a/src/utils/useLazyRef.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as React from 'react'; - -export default function useLazyRef(callback: () => T) { - const lazyRef = React.useRef(undefined); - - if (lazyRef.current === undefined) { - lazyRef.current = callback(); - } - - // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion - return lazyRef as React.MutableRefObject; -}