kandimat/redaktions-app/src/components/ChangeRole.tsx

100 lines
2.5 KiB
TypeScript

import React from "react";
import { IconButton, MenuItem } from "@material-ui/core";
import Menu from "@material-ui/core/Menu";
import EditIcon from "@material-ui/icons/Edit";
import { UppercaseUserRole, UPPERCASE_USER_ROLES } from "../jwt/jwt";
import { useMutation } from "@apollo/client";
import {
ChangeRoleResponse,
ChangeRoleVariables,
CHANGE_ROLE,
} from "../backend/mutations/userRole";
interface ChangeRoleProps {
currentRole: UppercaseUserRole;
currentUserRowId: number;
}
export default function ChangeRole(props: ChangeRoleProps): React.ReactElement {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const otherRoles = UPPERCASE_USER_ROLES.filter(
(role) => role != props.currentRole
);
const handleMenu = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const [changeRole] = useMutation<ChangeRoleResponse, ChangeRoleVariables>(
CHANGE_ROLE,
{
onCompleted() {
console.log("Role changed");
},
onError(e) {
console.error(e);
handleClose();
},
}
);
const displayRole = (role: UppercaseUserRole) => {
switch (role) {
case "CANDYMAT_CANDIDATE":
return "zu * machen";
case "CANDYMAT_EDITOR":
return "zu RedakteurIn machen";
case "CANDYMAT_PERSON":
return "zu Standard User machen";
}
};
return (
<React.Fragment>
<IconButton
aria-label="role of current user"
aria-controls="change-role"
aria-haspopup="true"
onClick={handleMenu}
color="inherit"
>
<EditIcon />
</IconButton>
<Menu
id="change-role"
anchorEl={anchorEl}
anchorOrigin={{
vertical: "top",
horizontal: "right",
}}
keepMounted
transformOrigin={{
vertical: "top",
horizontal: "right",
}}
open={open}
onClose={handleClose}
>
{otherRoles.map((role) => (
<MenuItem
key={role}
onClick={() => {
changeRole({
variables: {
personRowId: props.currentUserRowId,
newRole: role,
},
});
}}
>
{displayRole(role)}
</MenuItem>
))}
</Menu>
</React.Fragment>
);
}