umami/components/settings/UserButton.js

81 lines
2.2 KiB
JavaScript
Raw Normal View History

2022-10-28 01:42:57 +02:00
import useConfig from 'hooks/useConfig';
import useUser from 'hooks/useUser';
import { AUTH_TOKEN } from 'lib/constants';
import { removeItem } from 'next-basics';
import { useRouter } from 'next/router';
import { useRef, useState } from 'react';
import { Button, Icon, Item, Menu, Popup, Text } from 'react-basics';
import { FormattedMessage } from 'react-intl';
import useDocumentClick from 'hooks/useDocumentClick';
import Profile from 'assets/profile.svg';
import styles from './UserButton.module.css';
2020-08-06 08:03:07 +02:00
2022-10-13 01:29:44 +02:00
export default function UserButton() {
const [show, setShow] = useState(false);
const ref = useRef();
const user = useUser();
2020-08-06 08:03:07 +02:00
const router = useRouter();
2022-10-28 01:42:57 +02:00
const { adminDisabled } = useConfig();
2020-08-06 08:03:07 +02:00
const menuOptions = [
{
label: (
2020-09-07 10:22:16 +02:00
<FormattedMessage
id="label.logged-in-as"
defaultMessage="Logged in as {username}"
values={{ username: <b>{user.username}</b> }}
/>
2020-08-06 08:03:07 +02:00
),
value: 'username',
className: styles.username,
},
2022-10-13 00:35:33 +02:00
{
label: <FormattedMessage id="label.profile" defaultMessage="Profile" />,
value: 'profile',
2022-10-28 01:42:57 +02:00
hidden: adminDisabled,
divider: true,
2022-10-13 00:35:33 +02:00
},
2020-09-07 10:22:16 +02:00
{ label: <FormattedMessage id="label.logout" defaultMessage="Logout" />, value: 'logout' },
2020-08-06 08:03:07 +02:00
];
function handleClick() {
setShow(state => !state);
}
2020-08-06 08:03:07 +02:00
function handleSelect(value) {
2020-08-09 08:48:43 +02:00
if (value === 'logout') {
removeItem(AUTH_TOKEN);
router.push('/login');
} else if (value === 'profile') {
router.push('/profile');
2020-08-06 08:03:07 +02:00
}
}
useDocumentClick(e => {
if (!ref.current?.contains(e.target)) {
setShow(false);
}
});
2020-08-06 08:03:07 +02:00
return (
<div className={styles.button} ref={ref}>
<Button variant="light" onClick={handleClick}>
<Icon className={styles.icon} size="large">
<Profile />
</Icon>
</Button>
{show && (
<Popup className={styles.menu} position="bottom" gap={5}>
<Menu items={menuOptions} onSelect={handleSelect}>
{({ label, value }) => (
<Item key={value}>
<Text>{label}</Text>
</Item>
)}
</Menu>
</Popup>
)}
</div>
2020-08-06 08:03:07 +02:00
);
}