All files / src/components/shared/Navigation NavigationMenu.tsx

76.47% Statements 39/51
91.13% Branches 72/79
69.23% Functions 9/13
76% Lines 38/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321                                                                                        11x           150x 150x 150x       150x 150x 150x     150x 150x     150x   150x 2x 2x 2x                           150x         150x             150x 432x   150x                             150x 1030x     1030x 144x   144x   144x         2x                                                                             384x 384x 384x                                         48x 48x 48x                                                               886x 886x                                                           150x 3x                     6x                                                                           147x                              
/**
 * NavigationMenu Component
 * Story 1.17, Task 6b, 11b & 13b: Role-adaptive navigation menu with responsive design and performance optimization
 *
 * Renders navigation menu items based on user role.
 * Uses Material-UI components with Swiss design principles.
 * Supports icon-only mode for tablet layouts.
 * Wrapped with React.memo() for performance optimization (Task 13b).
 *
 * Items with `children` render as a dropdown (horizontal) or collapsible section (vertical).
 */
 
import React from 'react';
import {
  Box,
  Divider,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Menu,
  MenuItem,
  Collapse,
  Typography,
} from '@mui/material';
import { ExpandLess, ExpandMore, ArrowDropDown } from '@mui/icons-material';
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  getGroupedNavigationForRoles,
  getNavigationForRoles,
  isPathActive,
} from '@/config/navigationConfig';
import type { NavigationItem } from '@/config/navigationConfig';
import type { UserRole } from '@/types/auth';
 
interface NavigationMenuProps {
  userRoles: UserRole[];
  onItemClick?: () => void;
  showText?: boolean;
  variant?: 'horizontal' | 'vertical';
}
 
export const NavigationMenu = React.memo(function NavigationMenu({
  userRoles,
  onItemClick,
  showText = true,
  variant = 'horizontal',
}: NavigationMenuProps) {
  const { t } = useTranslation();
  const location = useLocation();
  const navigate = useNavigate();
  // Story 11.E.3 (cherry-pick 73d94688 / Story 9.5): when the user has more than one role,
  // render each role's nav items in its own section (section header + divider). Single-role
  // users see the existing flat list — no behavioural change for them.
  const isMultiRole = userRoles.length > 1;
  const navigationItems = isMultiRole ? [] : getNavigationForRoles(userRoles);
  const groupedNav = isMultiRole ? getGroupedNavigationForRoles(userRoles) : [];
 
  // Horizontal: track which group's popover menu is open
  const [menuAnchor, setMenuAnchor] = React.useState<HTMLElement | null>(null);
  const [openGroupPath, setOpenGroupPath] = React.useState<string | null>(null);
 
  // Vertical: track which groups are expanded
  const [expandedPaths, setExpandedPaths] = React.useState<Set<string>>(new Set());
 
  const handleGroupClick = (event: React.MouseEvent<HTMLElement>, path: string) => {
    if (variant === 'horizontal') {
      setMenuAnchor(event.currentTarget);
      setOpenGroupPath(path);
    } else E{
      setExpandedPaths((prev) => {
        const next = new Set(prev);
        if (next.has(path)) {
          next.delete(path);
        } else {
          next.add(path);
        }
        return next;
      });
    }
  };
 
  const handleMenuClose = () => {
    setMenuAnchor(null);
    setOpenGroupPath(null);
  };
 
  const handleChildClick = (path: string) => {
    handleMenuClose();
    navigate(path);
    onItemClick?.();
  };
 
  /** True if any child of this group is the active route */
  const isGroupActive = (item: NavigationItem) =>
    item.children?.some((child) => isPathActive(child.path, location.pathname)) ?? false;
 
  const itemSx = {
    borderRadius: 1,
    minWidth: showText ? 'auto' : '48px',
    justifyContent: showText ? 'flex-start' : 'center',
    px: showText ? 2 : 1,
    mb: variant === 'vertical' ? 0.5 : 0,
    '&.Mui-selected': {
      backgroundColor: 'primary.main',
      color: 'primary.contrastText',
      '&:hover': { backgroundColor: 'primary.dark' },
      '& .MuiListItemIcon-root': { color: 'primary.contrastText' },
    },
    '&:hover': { backgroundColor: 'action.hover' },
  };
 
  const renderItem = (item: NavigationItem) => {
    const Icon = item.icon;
 
    // ── Grouped item (has children) ──────────────────────────────────
    if (item.children && item.children.length > 0) {
      const groupActive = isGroupActive(item);
      const isOpen =
        variant === 'horizontal' ? openGroupPath === item.path : expandedPaths.has(item.path);
 
      return (
        <React.Fragment key={item.path}>
          <ListItem disablePadding>
            <ListItemButton
              selected={groupActive}
              onClick={(e) => handleGroupClick(e, item.path)}
              data-testid={`nav-group-${item.path.split('/').filter(Boolean).join('-')}`}
              aria-haspopup={variant === 'horizontal' ? 'true' : undefined}
              aria-expanded={isOpen}
              sx={itemSx}
            >
              <ListItemIcon sx={{ minWidth: showText ? 40 : 'auto', color: 'inherit' }}>
                <Icon />
              </ListItemIcon>
              {showText && (
                <ListItemText
                  primary={t(item.labelKey)}
                  primaryTypographyProps={{
                    variant: 'body2',
                    sx: { fontWeight: groupActive ? 600 : 400 },
                  }}
                />
              )}
              {showText &&
                (variant === 'horizontal' ? (
                  <ArrowDropDown sx={{ ml: 0.5, fontSize: 20 }} />
                ) : isOpen ? (
                  <ExpandLess />
                ) : (
                  <ExpandMore />
                ))}
            </ListItemButton>
          </ListItem>
 
          {/* Horizontal: popover Menu */}
          {variant === 'horizontal' && (
            <Menu
              anchorEl={menuAnchor}
              open={openGroupPath === item.path}
              onClose={handleMenuClose}
              anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
              transformOrigin={{ vertical: 'top', horizontal: 'left' }}
            >
              {item.children.map((child) => {
                const ChildIcon = child.icon;
                const childActive = isPathActive(child.path, location.pathname);
                return (
                  <MenuItem
                    key={child.path}
                    selected={childActive}
                    onClick={() => handleChildClick(child.path)}
                    data-testid={`nav-${child.path.split('/').filter(Boolean).join('-')}`}
                    sx={{ gap: 1.5 }}
                  >
                    <ChildIcon fontSize="small" sx={{ color: 'text.secondary' }} />
                    {t(child.labelKey)}
                  </MenuItem>
                );
              })}
            </Menu>
          )}
 
          {/* Vertical: inline Collapse */}
          {variant === 'vertical' && (
            <Collapse in={isOpen} unmountOnExit>
              <List disablePadding>
                {item.children.map((child) => {
                  const ChildIcon = child.icon;
                  const childActive = isPathActive(child.path, location.pathname);
                  return (
                    <ListItem key={child.path} disablePadding>
                      <ListItemButton
                        component={NavLink}
                        to={child.path}
                        selected={childActive}
                        onClick={onItemClick}
                        data-testid={`nav-${child.path.split('/').filter(Boolean).join('-')}`}
                        sx={{ ...itemSx, pl: 4 }}
                      >
                        <ListItemIcon sx={{ minWidth: 40, color: 'inherit' }}>
                          <ChildIcon />
                        </ListItemIcon>
                        <ListItemText
                          primary={t(child.labelKey)}
                          primaryTypographyProps={{
                            variant: 'body2',
                            sx: { fontWeight: childActive ? 600 : 400 },
                          }}
                        />
                      </ListItemButton>
                    </ListItem>
                  );
                })}
              </List>
            </Collapse>
          )}
        </React.Fragment>
      );
    }
 
    // ── Leaf item (no children) ──────────────────────────────────────
    const active = isPathActive(item.path, location.pathname);
    return (
      <ListItem key={item.path} disablePadding>
        <ListItemButton
          component={NavLink}
          to={item.path}
          selected={active}
          onClick={onItemClick}
          data-testid={`nav-${item.path.split('/').filter(Boolean).join('-')}`}
          sx={itemSx}
        >
          <ListItemIcon sx={{ minWidth: showText ? 40 : 'auto', color: 'inherit' }}>
            <Icon />
          </ListItemIcon>
          {showText && (
            <ListItemText
              primary={t(item.labelKey)}
              primaryTypographyProps={{
                variant: 'body2',
                sx: { fontWeight: active ? 600 : 400 },
              }}
            />
          )}
        </ListItemButton>
      </ListItem>
    );
  };
 
  // Story 11.E.3 / Story 9.5: multi-role users see each role's items in a labelled section
  // with a divider between groups. Section headers render only when text is visible (showText),
  // so the icon-only tablet layout stays compact.
  if (isMultiRole) {
    return (
      <nav aria-label={t('navigation.mainNav')} data-testid="navigation-menu-grouped">
        <Box
          sx={{
            display: 'flex',
            flexDirection: variant === 'horizontal' ? 'row' : 'column',
            alignItems: variant === 'horizontal' ? 'center' : 'stretch',
            gap: variant === 'horizontal' ? 1 : 0,
          }}
        >
          {groupedNav.map((group, idx) => (
            <React.Fragment key={group.role}>
              {idx > 0 && (
                <Divider
                  orientation={variant === 'horizontal' ? 'vertical' : 'horizontal'}
                  flexItem
                  sx={{ my: variant === 'vertical' ? 1 : 0, mx: variant === 'horizontal' ? 1 : 0 }}
                  data-testid={`nav-section-divider-${group.role}`}
                />
              )}
              {showText && variant === 'vertical' && (
                <Typography
                  variant="overline"
                  color="text.secondary"
                  sx={{ px: 2, pt: 1, display: 'block' }}
                  data-testid={`nav-section-header-${group.role}`}
                >
                  {t(group.labelKey)}
                </Typography>
              )}
              <List
                disablePadding
                sx={{
                  display: 'flex',
                  flexDirection: variant === 'horizontal' ? 'row' : 'column',
                  gap: variant === 'horizontal' ? 1 : 0,
                }}
                data-testid={`nav-section-${group.role}`}
                aria-label={t(group.labelKey)}
              >
                {group.items.map(renderItem)}
              </List>
            </React.Fragment>
          ))}
        </Box>
      </nav>
    );
  }
 
  return (
    <nav aria-label={t('navigation.mainNav')}>
      <List
        sx={{
          display: 'flex',
          flexDirection: variant === 'horizontal' ? 'row' : 'column',
          gap: variant === 'horizontal' ? 1 : 0,
          p: 0,
        }}
      >
        {navigationItems.map(renderItem)}
      </List>
    </nav>
  );
});