import { Menu, Transition } from '@headlessui/react'; import React, { Fragment, useState } from 'react'; import { useHistory } from 'react-router'; import { useDispatch, useSelector } from 'react-redux'; import { useCurrentUser } from '../../contexts'; import { SessionRoutePaths } from '../../routes'; import { RootState } from '../../services/store'; import { turnOff } from '../../services/store/unsavedChanges'; import { classNames } from '../../utils'; import { localFetch } from '../../utils/localFetch'; import { notEmpty } from '../../utils/notEmpty'; import { UserRole } from '../../__generated__/graphql-schema'; import { CurrentUserAvatar } from "../CurrentUserAvatar"; import { Dialog } from '../Dialog'; export const AppbarUserMenu = () => { const { user } = useCurrentUser(); const history = useHistory(); const [confirmLogout, setConfirmLogout] = useState(false) const [newPath, setNewPath] = useState() const unsavedChanges = useSelector((state: RootState) => state.unsavedChanges) const dispatch = useDispatch() const doLogout = () => { setConfirmLogout(false) dispatch(turnOff()) localFetch('/users/sign_out', { method: 'DELETE' }).then(() => { window.location.href = '/' }) } const handleLogout = () => { if (unsavedChanges && !confirmLogout) { setConfirmLogout(true) } else { doLogout() } } const handleForcedRedirect = () => { if (!newPath) return dispatch(turnOff()) setNewPath(undefined) history.push(newPath) } const handleLinkClick = (pathname: string) => { if (unsavedChanges) { setNewPath(pathname) } else { history.push(pathname) } } type MenuItem = { onClick: Function label: string } const menuItems: MenuItem[] = [ { onClick: () => { handleLinkClick(SessionRoutePaths.show) }, label: 'Perfil' }, { onClick: handleLogout, label: 'Sair' } ] if (user?.roles.includes(UserRole.Admin)) { menuItems.push({ onClick: () => { window.location.href = '/admin'}, label: 'Painel de Administração' }) } return ( <> setNewPath(value ? newPath : undefined)} onConfirmation={handleForcedRedirect} title="Modificações não Salvas" text="Todas as alterações serão descartadas. Deseja continuar?" /> {({ open }) => ( <> {user?.name}
{menuItems.map((item) => (
{ item.onClick() }} > {({ active }) => ( {item.label} )}
))}
)}
) }