Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3585 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Badge, styled, Menu, MenuItem } from '@mui/material';
import { useDispatch } from 'react-redux';

import { getAdminUrl } from '@app/services/admin';
import { addNotification } from '@app/redux/notification/notification.actions';

const NavItem = styled('div')(({ theme }) => ({
  position: 'relative',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  justifyContent: 'center',
  padding: theme.spacing(1, 0),
  fontSize: '12px',
  fontWeight: 400,
  height: '100%',
  cursor: 'pointer',
  '&::after': {
    borderBottom: '2px solid var(--font-color)',
    content: '""',
    bottom: '-1px',
    left: 0,
    position: 'absolute',
    transform: 'scaleX(0)',
    transition: 'transform 0.2s ease-in-out',
    width: '100%'
  },
  '&.active::after, &:hover::after': {
    transform: 'scaleX(1)'
  },
  [theme.breakpoints.up('lg')]: {
    minWidth: '60px'
  },
  [theme.breakpoints.down('md')]: {
    fontSize: 0
  }
}));

const NavigationItem = ({ ajax = 0, url = '', childs = [], count = 0, onClick, children }) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const open = Boolean(anchorEl);

  const navigate = useNavigate();
  const dispatch = useDispatch();

  const handleClose = () => {
    setAnchorEl(null);
  };

  const openAdmin = async () => {
    try {
      const adminUrl = await getAdminUrl(url);
      window.open(adminUrl, '_blank');
    } catch (error) {
      dispatch(addNotification({ style: 'danger', msg: error.message }));
    }
  };

  const handleClick = async (e) => {
    e.preventDefault();

    if (ajax) {
      openAdmin();
      return;
    }

    if (onClick) {
      onClick();
      return;
    }

    if (childs.length) {
      setAnchorEl(e.currentTarget);
      return;
    }

    navigate(`/${url}`);
  };

  const handleMenuClick = (childUrl) => {
    navigate(`/${childUrl}`);
    handleClose();
  };

  return (
    <li>
      <NavItem onClick={handleClick} className={open ? 'active' : ''}>
        {children}
        <Badge
          badgeContent={count}
          color='error'
          sx={{ position: 'absolute', top: '1rem', right: '1rem' }}
        />
      </NavItem>
      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        transformOrigin={{ horizontal: 'right', vertical: 'top' }}
        anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
      >
        {childs.map((child) => (
          <MenuItem key={child.href} onClick={() => handleMenuClick(child.href)}>
            {child.label}
          </MenuItem>
        ))}
      </Menu>
    </li>
  );
};

export default NavigationItem;