Refactor base app layout

This commit is contained in:
schroda
2024-07-11 17:22:52 +02:00
parent 31837392b5
commit f43b7af3cd
19 changed files with 443 additions and 288 deletions

View File

@@ -6,12 +6,11 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import React, { useContext } from 'react';
import { useCallback, useContext, useMemo, useRef } from 'react';
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import Box from '@mui/material/Box';
import CollectionsBookmarkIcon from '@mui/icons-material/CollectionsBookmark';
import CollectionsOutlinedBookmarkIcon from '@mui/icons-material/CollectionsBookmarkOutlined';
import NewReleasesIcon from '@mui/icons-material/NewReleases';
@@ -23,15 +22,17 @@ import GetAppOutlinedIcon from '@mui/icons-material/GetAppOutlined';
import SettingsIcon from '@mui/icons-material/Settings';
import ArrowBack from '@mui/icons-material/ArrowBack';
import { useLocation } from 'react-router-dom';
import { createPortal } from 'react-dom';
import ArrowForwardIcon from '@mui/icons-material/ArrowForward';
import MenuIcon from '@mui/icons-material/Menu';
import Stack from '@mui/material/Stack';
import { NavbarItem } from '@/typings';
import { NavBarContext } from '@/components/context/NavbarContext';
import { DesktopSideBar } from '@/components/navbar/navigation/DesktopSideBar';
import { MobileBottomBar } from '@/components/navbar/navigation/MobileBottomBar';
import { useBackButton } from '@/util/useBackButton.ts';
import { getOptionForDirection } from '@/theme.ts';
import { MediaQuery } from '@/lib/ui/MediaQuery.tsx';
import { DesktopSideBar } from '@/components/navbar/navigation/DesktopSideBar.tsx';
import { useResizeObserver } from '@/util/useResizeObserver.tsx';
import { MobileBottomBar } from '@/components/navbar/navigation/MobileBottomBar.tsx';
const navbarItems: Array<NavbarItem> = [
{
@@ -72,7 +73,8 @@ const navbarItems: Array<NavbarItem> = [
];
export function DefaultNavBar() {
const { title, action, override } = useContext(NavBarContext);
const { title, action, override, isCollapsed, setIsCollapsed, setAppBarHeight, navBarWidth } =
useContext(NavBarContext);
const { pathname } = useLocation();
const handleBack = useBackButton();
@@ -80,59 +82,91 @@ export function DefaultNavBar() {
const isMobileWidth = MediaQuery.useIsMobileWidth();
const isMainRoute = navbarItems.some(({ path }) => path === pathname);
const actualNavBarWidth = isMobileWidth || isCollapsed ? 0 : navBarWidth;
const appBarRef = useRef<HTMLDivElement | null>(null);
useResizeObserver(
appBarRef,
useCallback(() => setAppBarHeight(appBarRef.current?.clientHeight ?? 0), [appBarRef]),
);
const activeNavBar: NavbarItem['show'] = isMobileWidth ? 'mobile' : 'desktop';
const visibleNavBarItems = useMemo(
() => navbarItems.filter(({ show }) => ['both', activeNavBar].includes(show)),
[isMobileWidth],
);
const NavBarComponent = useMemo(() => (isMobileWidth ? MobileBottomBar : DesktopSideBar), [isMobileWidth]);
const navBar = useMemo(
() => <NavBarComponent navBarItems={visibleNavBarItems} />,
[NavBarComponent, visibleNavBarItems],
);
// Allow default navbar to be overrided
if (override.status) return override.value;
let navbar: JSX.Element | null = null;
if (isMobileWidth) {
if (isMainRoute) {
navbar = <MobileBottomBar navBarItems={navbarItems.filter((it) => it.show !== 'desktop')} />;
}
} else {
navbar = <DesktopSideBar navBarItems={navbarItems.filter((it) => it.show !== 'mobile')} />;
}
return (
<Box sx={{ flexGrow: 1 }}>
<AppBar position="fixed" color="default">
<Toolbar>
{!isMainRoute && (
<IconButton
component="button"
edge="start"
sx={{ marginRight: 2 }}
color="inherit"
aria-label="menu"
size="large"
onClick={handleBack}
<>
<AppBar
ref={appBarRef}
sx={{
position: 'fixed',
marginLeft: actualNavBarWidth,
width: `calc(100% - ${actualNavBarWidth}px)`,
zIndex: (theme) => theme.zIndex.drawer + 1,
}}
color="default"
>
<Toolbar sx={{ position: 'relative' }}>
{!isMobileWidth && (
<Stack
sx={{
position: 'absolute',
left: 0,
width: navBarWidth,
...(!isCollapsed && { display: 'none' }),
alignItems: 'center',
}}
>
{getOptionForDirection(<ArrowBack />, <ArrowForwardIcon />)}
</IconButton>
<IconButton color="inherit" aria-label="open drawer" onClick={() => setIsCollapsed(false)}>
<MenuIcon />
</IconButton>
</Stack>
)}
<Typography
variant={isMobileWidth ? 'h6' : 'h5'}
sx={{ flexGrow: 1 }}
noWrap
textOverflow="ellipsis"
<Stack
sx={{
ml: `${isCollapsed ? navBarWidth : 0}px`,
width: '100%',
flexDirection: 'row',
alignItems: 'center',
}}
>
{title}
</Typography>
{action}
<div id="navbarToolbar" />
{!isMainRoute && (
<IconButton
edge="start"
component="button"
sx={{ marginRight: 2 }}
size="large"
color="inherit"
aria-label="menu"
onClick={handleBack}
>
{getOptionForDirection(<ArrowBack />, <ArrowForwardIcon />)}
</IconButton>
)}
<Typography
variant={isMobileWidth ? 'h6' : 'h5'}
sx={{ flexGrow: 1 }}
noWrap
textOverflow="ellipsis"
>
{title}
</Typography>
{action}
</Stack>
</Toolbar>
</AppBar>
{navbar}
</Box>
{!isMobileWidth || isMainRoute ? navBar : null}
</>
);
}
interface INavbarToolbarProps {
children?: React.ReactNode;
}
export const NavbarToolbar: React.FC<INavbarToolbarProps> = ({ children }) => {
const container = document.getElementById('navbarToolbar');
if (!container) return null;
return createPortal(children, container);
};

View File

@@ -10,6 +10,7 @@ import React, { useCallback, useMemo, useState } from 'react';
import { INavbarOverride } from '@/typings';
import { NavBarContext } from '@/components/context/NavbarContext';
import { useHistory } from '@/util/useHistory.ts';
import { useLocalStorage } from '@/util/useStorage.tsx';
interface IProps {
children: React.ReactNode;
@@ -18,10 +19,14 @@ interface IProps {
export function NavBarContextProvider({ children }: IProps) {
const [title, setTitle] = useState<string | React.ReactNode>('Suwayomi');
const [action, setAction] = useState<any>(<div />);
const [appBarHeight, setAppBarHeight] = useState(0);
const [override, setOverride] = useState<INavbarOverride>({
status: false,
value: <div />,
});
const [isCollapsed, setIsCollapsed] = useLocalStorage('NavBar::isCollapsed', false);
const [navBarWidth, setNavBarWidth] = useState(0);
const [bottomBarHeight, setBottomBarHeight] = useState(0);
const history = useHistory();
@@ -38,12 +43,36 @@ export function NavBarContextProvider({ children }: IProps) {
history,
title,
setTitle: updateTitle,
appBarHeight,
setAppBarHeight,
action,
setAction,
override,
setOverride,
isCollapsed,
setIsCollapsed,
navBarWidth,
setNavBarWidth,
bottomBarHeight,
setBottomBarHeight,
}),
[history, title, updateTitle, action, setAction, override, setOverride],
[
history,
title,
updateTitle,
appBarHeight,
setAppBarHeight,
action,
setAction,
override,
setOverride,
isCollapsed,
setIsCollapsed,
navBarWidth,
setNavBarWidth,
bottomBarHeight,
setBottomBarHeight,
],
);
return <NavBarContext.Provider value={value}>{children}</NavBarContext.Provider>;
}

View File

@@ -6,56 +6,116 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import Drawer from '@mui/material/Drawer';
import List from '@mui/material/List';
import ListItemIcon from '@mui/material/ListItemIcon';
import Tooltip from '@mui/material/Tooltip';
import ListItemButton from '@mui/material/ListItemButton';
import { styled, useTheme } from '@mui/material/styles';
import { Link, useLocation } from 'react-router-dom';
import ListItemText from '@mui/material/ListItemText';
import { useTranslation } from 'react-i18next';
import { NavbarItem } from '@/typings';
import { useLocation } from 'react-router-dom';
import IconButton from '@mui/material/IconButton';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import Divider from '@mui/material/Divider';
import { styled, useTheme } from '@mui/material/styles';
import { useCallback, useEffect, useMemo, useRef } from 'react';
import Box from '@mui/material/Box';
import ListItem from '@mui/material/ListItem';
import Tooltip from '@mui/material/Tooltip';
import { NavbarItem } from '@/typings.ts';
import { ListItemLink } from '@/components/util/ListItemLink.tsx';
import { getOptionForDirection } from '@/theme.ts';
import { useNavBarContext } from '@/components/context/NavbarContext.tsx';
import { useResizeObserver } from '@/util/useResizeObserver.tsx';
const SideNavBarContainer = styled('div')(({ theme }) => ({
height: '100vh',
width: theme.spacing(8),
backgroundColor: theme.palette.custom.dark,
position: 'fixed',
top: 0,
left: 0,
paddingTop: theme.spacing(8),
const DrawerHeader = styled('div')(({ theme }) => ({
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'flex-end',
padding: theme.spacing(0, 1),
// necessary for content to be below app bar
...theme.mixins.toolbar,
}));
interface IProps {
navBarItems: Array<NavbarItem>;
}
export function DesktopSideBar({ navBarItems }: IProps) {
const NavigationBarItem = ({ path, title, IconComponent, SelectedIconComponent }: NavbarItem) => {
const { t } = useTranslation();
const location = useLocation();
const { isCollapsed } = useNavBarContext();
const theme = useTheme();
const iconFor = (path: string, IconComponent: any, SelectedIconComponent: any) => {
if (location.pathname === path)
return <SelectedIconComponent sx={{ color: 'primary.main' }} fontSize="large" />;
return (
<IconComponent sx={{ color: theme.palette.mode === 'dark' ? 'grey.A400' : 'grey.600' }} fontSize="large" />
);
};
const isActive = path === location.pathname;
const Icon = isActive ? SelectedIconComponent : IconComponent;
const { listItemProps, listItemIconProps } = useMemo(
() => ({
listItemProps: isCollapsed ? { p: 0.5, display: 'flex', flexDirection: 'column' } : {},
listItemIconProps: isCollapsed ? { justifyContent: 'center' } : {},
}),
[isCollapsed],
);
return (
<SideNavBarContainer>
{navBarItems.map(({ path, title, IconComponent, SelectedIconComponent }: NavbarItem) => (
<Link to={path} style={{ color: 'inherit', textDecoration: 'none' }} key={path}>
<ListItemButton disableRipple key={title}>
<ListItemIcon sx={{ minWidth: '0' }}>
<Tooltip placement="right" title={t(title)}>
{iconFor(path, IconComponent, SelectedIconComponent)}
</Tooltip>
</ListItemIcon>
</ListItemButton>
</Link>
))}
</SideNavBarContainer>
<ListItemLink selected={!isCollapsed && isActive} sx={{ p: 0, m: 0 }} to={path}>
<Tooltip title={t(title)} placement="right">
<ListItem sx={listItemProps}>
<ListItemIcon sx={listItemIconProps}>
<Icon sx={{ color: isActive ? 'primary.main' : undefined }} />
</ListItemIcon>
<ListItemText
primary={t(title)}
sx={{ maxWidth: '100%' }}
primaryTypographyProps={{
sx: {
maxWidth: '100%',
overflow: 'hidden',
textOverflow: 'ellipsis',
...(isCollapsed ? theme.typography.caption : {}),
color: isActive ? 'primary.main' : undefined,
},
}}
/>
</ListItem>
</Tooltip>
</ListItemLink>
);
}
};
const MIN_WIDTH_COLLAPSED = undefined;
const MAX_WIDTH_COLLAPSED = 120;
const MIN_WIDTH_EXTENDED = 240;
const MAX_WIDTH_EXTENDED = 400;
export const DesktopSideBar = ({ navBarItems }: { navBarItems: NavbarItem[] }) => {
const { isCollapsed, setIsCollapsed, navBarWidth, setNavBarWidth } = useNavBarContext();
useEffect(() => () => setNavBarWidth(0), []);
const ref = useRef<HTMLDivElement | null>(null);
useResizeObserver(
ref,
useCallback(() => setNavBarWidth(ref.current?.clientWidth ?? 0), [ref]),
);
return (
<Drawer variant="permanent" sx={{ width: navBarWidth }}>
<Box
ref={ref}
sx={{
minWidth: isCollapsed ? MIN_WIDTH_COLLAPSED : MIN_WIDTH_EXTENDED,
maxWidth: isCollapsed ? MAX_WIDTH_COLLAPSED : MAX_WIDTH_EXTENDED,
}}
>
<DrawerHeader>
<IconButton onClick={() => setIsCollapsed(true)}>
{getOptionForDirection(<ChevronLeftIcon />, <ChevronRightIcon />)}
</IconButton>
</DrawerHeader>
<Divider />
<List sx={{ p: 1 }} dense={isCollapsed}>
{navBarItems.map((navBarItem) => (
<NavigationBarItem key={navBarItem.path} {...navBarItem} />
))}
</List>
</Box>
</Drawer>
);
};

View File

@@ -6,76 +6,58 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import Box from '@mui/material/Box';
import ListItemButton from '@mui/material/ListItemButton';
import { styled, useTheme } from '@mui/material/styles';
import { Link as RRDLink, useLocation } from 'react-router-dom';
import BottomNavigation from '@mui/material/BottomNavigation';
import BottomNavigationAction from '@mui/material/BottomNavigationAction';
import { useTranslation } from 'react-i18next';
import { NavbarItem } from '@/typings';
import Paper from '@mui/material/Paper';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { NavbarItem } from '@/typings.ts';
import { useResizeObserver } from '@/util/useResizeObserver.tsx';
import { useNavBarContext } from '@/components/context/NavbarContext.tsx';
const BottomNavContainer = styled('div')(({ theme }) => ({
bottom: 0,
left: 0,
height: theme.spacing(7),
width: '100vw',
backgroundColor: theme.palette.custom.light,
position: 'fixed',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'center',
// For Some reason the theme is throwing and error when accessing the Zindex object,
// This is the zIndex of the appBar in the default theme
zIndex: 1100,
}));
const Link = styled(RRDLink)({
textDecoration: 'none',
flex: 1,
});
interface IProps {
navBarItems: Array<NavbarItem>;
}
export function MobileBottomBar({ navBarItems }: IProps) {
export const MobileBottomBar = ({ navBarItems }: { navBarItems: NavbarItem[] }) => {
const { t } = useTranslation();
const { setBottomBarHeight } = useNavBarContext();
const location = useLocation();
const theme = useTheme();
const navigate = useNavigate();
const iconFor = (path: string, IconComponent: any, SelectedIconComponent: any) => {
if (location.pathname === path)
return <SelectedIconComponent sx={{ color: 'primary.main' }} fontSize="medium" />;
return (
<IconComponent sx={{ color: theme.palette.mode === 'dark' ? 'grey.A400' : 'grey.600' }} fontSize="medium" />
);
};
useEffect(() => () => setBottomBarHeight(0), []);
const ref = useRef<HTMLDivElement | null>(null);
useResizeObserver(
ref,
useCallback(() => setBottomBarHeight(ref.current?.clientHeight ?? 0), [ref]),
);
const [selectedNavBarItem, setSelectedNavBarItem] = useState(
navBarItems.find((navBarItem) => navBarItem.path === location.pathname)?.path,
);
return (
<BottomNavContainer>
{navBarItems.map(({ path, title, IconComponent, SelectedIconComponent }: NavbarItem) => (
<Link to={path} key={path}>
<ListItemButton disableRipple sx={{ justifyContent: 'center', padding: '8px' }} key={title}>
<Box display="flex" flexDirection="column" alignItems="center">
{iconFor(path, IconComponent, SelectedIconComponent)}
<Box
sx={{
fontSize: '0.65rem',
color:
// eslint-disable-next-line no-nested-ternary
location.pathname === path
? 'primary.main'
: theme.palette.mode === 'dark'
? 'grey.A400'
: 'grey.600',
}}
>
{t(title)}
</Box>
</Box>
</ListItemButton>
</Link>
))}
</BottomNavContainer>
<Paper
ref={ref}
sx={{ position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: (theme) => theme.zIndex.drawer - 1 }}
elevation={3}
>
<BottomNavigation
sx={{ backgroundColor: 'custom.light' }}
showLabels
value={selectedNavBarItem}
onChange={(_, newValue: string) => {
setSelectedNavBarItem(newValue);
navigate(newValue);
}}
>
{navBarItems.map(({ path, title, IconComponent, SelectedIconComponent }) => (
<BottomNavigationAction
key={path}
value={path}
label={t(title)}
icon={selectedNavBarItem === path ? <SelectedIconComponent /> : <IconComponent />}
/>
))}
</BottomNavigation>
</Paper>
);
}
};