All files / src/components Header.tsx

84% Statements 42/50
76.47% Branches 26/34
88.88% Functions 8/9
85.41% Lines 41/48

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                                                                            20x 279x 279x 279x 279x 279x         279x 3x 3x 3x 3x       279x 137x 3x   134x         279x 3x 2x 2x         279x 279x 279x                     279x   269x 269x       279x 138x 138x 2x     138x 138x 11x 127x 14x   113x       279x 279x   279x                           279x                       1x     2x                              
/**
 * @file Header.tsx
 * @description
 * Main application header with navigation, language, and theme controls.
 *
 * **Features:**
 * - Dynamic page titles based on user role
 * - Dark mode toggle with localStorage persistence
 * - Language switcher (English/Deutsch)
 * - Logout/back navigation button
 * - Responsive design with Tailwind CSS
 *
 * **Props:**
 * - `isLoggedIn` - User authentication state
 * - `onLogout` - Custom logout handler (optional)
 * - `hideBackButton` - Hide navigation/logout button
 *
 * @component
 */
 
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate } from 'react-router-dom';
import { FaMoon, FaSun } from 'react-icons/fa';
import '../styles/header.css';
 
interface HeaderProps {
  isLoggedIn: boolean;
  onLogout?: () => void;
  hideBackButton?: boolean;
}
 
/**
 * Application header component
 * @component
 * @param {HeaderProps} props - Component props
 * @returns {JSX.Element} Header with controls
 */
const Header: React.FC<HeaderProps> = ({ isLoggedIn, onLogout, hideBackButton = false }) => {
  const { t, i18n } = useTranslation(['translation', 'help']);
  const location = useLocation();
  const navigate = useNavigate();
  const [title, setTitle] = useState('');
  const [darkMode, setDarkMode] = useState<boolean>(
    localStorage.getItem('darkMode') === 'enabled'
  );
 
  // Toggle dark mode and update document class
  const toggleDarkMode = () => {
    const newMode = !darkMode;
    setDarkMode(newMode);
    localStorage.setItem('darkMode', newMode ? 'enabled' : 'disabled');
    document.documentElement.classList.toggle('dark', newMode);
  };
 
  // Apply dark mode on component mount/change
  useEffect(() => {
    if (darkMode) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
  }, [darkMode]);
 
  // Change language and persist in localStorage
  const changeLanguage = (lng: string) => {
    if (i18n.language !== lng) {
      localStorage.setItem('language', lng);
      i18n.changeLanguage(lng);
    }
  };
 
  // Map route to translation key
  const getPageKey = () => {
    const path = location.pathname;
    const pathMap: Record<string, string> = {
      '/admin': 'adminDashboard',
      '/user': 'userDashboard',
      '/login': 'login',
      '/add-product': 'addProduct',
      '/delete-product': 'deleteProduct',
      '/list-stock': 'listStock',
      '/search-product': 'searchProduct',
    };
    
    // Check exact matches first, then path prefixes for dynamic routes
    if (pathMap[path]) return pathMap[path];
    // Product edit route uses dynamic ID in path (e.g., /product/123/edit)
    Iif (path.startsWith('/product/')) return 'changeProduct';
    return 'default';
  };
 
  // Set title based on user role
  useEffect(() => {
    const savedLanguage = localStorage.getItem('language') || 'en';
    if (i18n.language !== savedLanguage) {
      i18n.changeLanguage(savedLanguage);
    }
 
    const role = localStorage.getItem('role');
    if (role === 'ROLE_ADMIN') {
      setTitle(t('adminDashboard.title'));
    } else if (role === 'ROLE_USER') {
      setTitle(t('userDashboard.title'));
    } else {
      setTitle(t('header.defaultTitle'));
    }
  }, [i18n, i18n.language, location.pathname, t]);
 
  const isDashboard = location.pathname === '/admin' || location.pathname === '/user';
  const buttonLabel = isDashboard ? t('header.logout') : t(`${getPageKey()}.backToDashboard`);
 
  const handleButtonClick = () => {
    if (isDashboard) {
      if (onLogout) {
        onLogout();
      } else {
        localStorage.clear();
        navigate('/login', { replace: true });
      }
    } else {
      const role = localStorage.getItem('role');
      navigate(role === 'ROLE_ADMIN' ? '/admin' : '/user', { replace: true });
    }
  };
 
  return (
    <header className="header-container">
      <div>
        <h1 className="header-title">{title}</h1>
        <p className="header-subtitle">{t('header.subtitle')}</p>
      </div>
 
      <div className="header-buttons">
        <button className="dark-mode-button" onClick={toggleDarkMode}>
          {darkMode ? <FaMoon size={20} /> : <FaSun size={20} />}
        </button>
 
        <button className="language-button" onClick={() => changeLanguage('en')}>
          🇬🇧 English
        </button>
        <button className="language-button" onClick={() => changeLanguage('de')}>
          🇩🇪 Deutsch
        </button>
 
        {isLoggedIn && !hideBackButton && (
          <button onClick={handleButtonClick} className="logout-button">
            {buttonLabel}
          </button>
        )}
      </div>
    </header>
  );
};
 
export default Header;