@material-ui/core#Menu JavaScript Examples

The following examples show how to use @material-ui/core#Menu. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JoinMenu.jsx    From frontend with MIT License 6 votes vote down vote up
JoinMenu = () => {
  const [anchorEl, setAnchorEl] = React.useState(null);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };
  return (
    <div>
      <Button onClick={handleClick} className="join-button">
        {plusIcon}
        <span className="text">Долучитися</span>
        <ArrowDropDownIcon />
      </Button>
      <Menu
        id="join-menu"
        className="join-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >
        <MenuItem onClick={handleClose} className="join-menu-item">
          <Icon style={{ color: '#1540A4' }}>store</Icon>
          <span>Як Організація</span>
        </MenuItem>
        <MenuItem onClick={handleClose} className="join-menu-item">
          <Icon style={{ color: '#1540A4' }}>person</Icon>
          <span>Як Волонтер</span>
        </MenuItem>
      </Menu>
    </div>
  );
}
Example #2
Source File: unlockMenu.jsx    From keep3r.governance with MIT License 6 votes vote down vote up
render() {

    const {
      classes,
      handleClose,
      anchorEl
    } = this.props

    return (
      <Menu
        anchorEl={ anchorEl }
        keepMounted
        open={ Boolean(anchorEl) }
        onClose={ handleClose }
      >
        { this.renderMenuItems() }
        <MenuItem onClick={ () => { this.handleDisconnect() } } className={ classes.text }>
          <ExitToAppIcon className={ classes.icon } />
          Disconnect
        </MenuItem>
      </Menu>
    )
  }
Example #3
Source File: component.jsx    From wiki with GNU General Public License v3.0 6 votes vote down vote up
StyledMenu = withStyles({
  paper: {
    border: '1px solid #d3d4d5',
  },
})((props) => (
  <Menu
    elevation={0}
    getContentAnchorEl={null}
    anchorOrigin={{
      vertical: 'bottom',
      horizontal: 'center',
    }}
    transformOrigin={{
      vertical: 'top',
      horizontal: 'center',
    }}
    {...props}
  />
))
Example #4
Source File: UserMoreMenu.js    From course-manager with MIT License 6 votes vote down vote up
function UserMoreMenu({ id }) {
  const navigate = useNavigate();
  const ref = useRef(null);
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <IconButton ref={ref} onClick={() => setIsOpen(true)}>
        <Icon icon={moreVerticalFill} width={20} height={20} />
      </IconButton>

      <Menu
        open={isOpen}
        anchorEl={ref.current}
        onClose={() => setIsOpen(false)}
        PaperProps={{
          sx: { width: 200, maxWidth: '100%' }
        }}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'right' }}
      >
        <MenuItem sx={{ color: 'text.secondary' }} onClick={() => navigate(id)}>
          <ListItemIcon>
            <Icon icon={trash2Outline} width={24} height={24} />
          </ListItemIcon>
          <ListItemText primary="Delete" primaryTypographyProps={{ variant: 'body2' }} />
        </MenuItem>

        <MenuItem component={RouterLink} to="#" sx={{ color: 'text.secondary' }}>
          <ListItemIcon>
            <Icon icon={editFill} width={24} height={24} />
          </ListItemIcon>
          <ListItemText primary="Create" primaryTypographyProps={{ variant: 'body2' }} />
        </MenuItem>
      </Menu>
    </>
  );
}
Example #5
Source File: MenuBar.js    From A2 with GNU General Public License v3.0 5 votes vote down vote up
export default function MenuBar(props) {
  const classes = useStyles();
  const [auth] = React.useState(true);
  const [anchorEl, setAnchorEl] = React.useState(null);
  const open = Boolean(anchorEl);

  const handleMenu = event => {
    setAnchorEl(event.currentTarget);
  };

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

  return (
    <UserContext.Consumer>
      {({ username }) => (
        <div className={classes.root}>
          <AppBar position="static" className={styles.appBar} color="white">
            <Toolbar>
              <IconButton
                edge="start"
                className={classes.menuButton}
                color="pink"
                aria-label="menu"
                onClick={props.toggleSidebar}
              >
                <MenuIcon />
              </IconButton>
              <Typography variant="h6" className={classes.title} />
              {auth && (
                <div className={styles.menuBar}>
                  <h3 className={styles.profileName}>{username}</h3>
                  <IconButton
                    aria-label="account of current user"
                    aria-controls="menu-appbar"
                    aria-haspopup="true"
                    onClick={handleMenu}
                    color="pink"
                  >
                    <AccountCircle />
                  </IconButton>
                  <Menu
                    id="menu-appbar"
                    anchorEl={anchorEl}
                    anchorOrigin={{
                      vertical: "top",
                      horizontal: "right"
                    }}
                    keepMounted
                    transformOrigin={{
                      vertical: "top",
                      horizontal: "right"
                    }}
                    open={open}
                    onClose={handleClose}
                  >
                    <MenuItem onClick={handleClose}>Profile</MenuItem>
                    <MenuItem onClick={handleClose}>My account</MenuItem>
                  </Menu>
                </div>
              )}
            </Toolbar>
          </AppBar>
        </div>
      )}
    </UserContext.Consumer>
  );
}
Example #6
Source File: SideUser.js    From gedge-platform with Apache License 2.0 5 votes vote down vote up
SideUser = () => {
    const classes = useStyles();
    const [anchorEl, setAnchorEl] = React.useState(null);

    const handleUserOpen = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handleUserClose = () => {
        setAnchorEl(null);
    };
    const handleItemClick = () => {
        handleUserClose();
    };
    
    const [username, SetUsername] = React.useState("")


    useEffect(() => {
        if (localStorage.getItem("logonUser")) {
            // const obj = JSON.parse(localStorage.getItem("authUser"));
            // const uNm = obj.email.split("@")[0];
            // username = uNm.charAt(0).toUpperCase() + uNm.slice(1);
            SetUsername(localStorage.getItem("logonUser"))
        }
    }, []);


    return (
        <UserArea className="hasNotify">
            <BtnArea>
                <button
                    type="button"
                    onClick={handleUserOpen}
                >
                    <img className="avatar" src={avatar2}></img>
                    <span className="name">{username}</span>
                </button>
                <Menu
                    id="simple-menu"
                    anchorEl={anchorEl}
                    keepMounted
                    open={Boolean(anchorEl)}
                    onClose={handleUserClose}
                    getContentAnchorEl={null}
                    anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
                    className={classes.popover}
                >
                    {/* <MenuItem
                        onClick={handleItemClick}
                    >
                        <Link to="/Notify">알림 보기</Link>
                    </MenuItem> */}
                    <MenuItem
                        onClick={handleItemClick}
                    >
                        사용자 정보
                    </MenuItem>
                    <MenuItem
                        onClick={handleItemClick}
                    >
                        <Link to="/logout">로그아웃</Link>
                    </MenuItem>
                </Menu>
            </BtnArea>
        </UserArea>
    )
}
Example #7
Source File: MobileEditMenu.js    From inventory-management-web with MIT License 5 votes vote down vote up
MobileEditMenu = ({ handleDelete, handleEdit, row }) => {
  // set anchor for menu
  const [anchorEl, setAnchorEl] = useState(null);

  const classes = useStyles();

  // handle menu open
  const handleMenuClick = event => {
    setAnchorEl(event.currentTarget);
  };

  // handle menu close by selecting edit or delete action
  const handleMenuClose = (option, param) => {
    if (option) {
      if (option === 'Edit') {
        handleEdit(param);
      } else if (option === 'Delete') {
        handleDelete(param);
      }
    }
    setAnchorEl(null);
  };

  return (
    <>
      <IconButton onClick={handleMenuClick}>
        <MenuIcon className={classes.menuIcon} />
      </IconButton>
      <Menu
        elevation={3}
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
      >
        <MenuItem
          onClick={() => {
            handleMenuClose('Edit', row);
          }}
          className={classes.menuItem}
        >
          <EditIcon /> Edit
        </MenuItem>
        <MenuItem
          onClick={() => {
            handleMenuClose('Delete', row);
          }}
          className={classes.menuItem}
        >
          <DeleteIcon /> Delete
        </MenuItem>
      </Menu>
    </>
  );
}
Example #8
Source File: Song.js    From Octave with MIT License 5 votes vote down vote up
function Song({ data }) {
  const [anchorEl, setAnchorEl] = useState(null);
  const [snackBar, setSnackBar] = useState(null);
  const [isModalOpen, SetIsModalOpen] = useState(false);
  const { playSong, playNext, addToQueue, addToFavourites } = useSongFunctions(
    data,
    setAnchorEl,
    setSnackBar
  );

  const openOptions = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const openAddSongPlaylistModal = () => {
    SetIsModalOpen(true);
    setAnchorEl(false);
  };

  return (
    <div className="song">
      <img src={data.imageUrl} alt="" className="song__image" />
      <p className="song__name" title={data.name}>
        {data.name}
      </p>
      <p className="song__artist" title={data.artist}>
        {data.artist}
      </p>
      <div className="song__playButton">
        <IconButton className="song__playIcon" onClick={playSong}>
          <PlayCircleFilledWhiteIcon style={{ fill: "#F22C89" }} />
        </IconButton>
      </div>
      <div className="song__option">
        <IconButton
          className="song__optionIcon"
          aria-controls="simple-menu"
          aria-haspopup="true"
          onClick={openOptions}
        >
          <MoreVertIcon />
        </IconButton>
        <Menu
          id="simple-menu"
          anchorEl={anchorEl}
          keepMounted
          open={Boolean(anchorEl)}
          onClose={() => setAnchorEl(false)}
        >
          <MenuItem className="song__optionItem" onClick={playNext}>
            Play Next
          </MenuItem>
          <MenuItem className="song__optionItem" onClick={addToQueue}>
            Add to Queue
          </MenuItem>
          <MenuItem className="song__optionItem" onClick={addToFavourites}>
            Add To Favourites
          </MenuItem>
          <MenuItem
            className="song__optionItem"
            onClick={openAddSongPlaylistModal}
          >
            Add To Playlist
          </MenuItem>
        </Menu>
      </div>
      {snackBar && <SnackBar snackBar={snackBar} setSnackBar={setSnackBar} />}{" "}
      {/* To Show Pop Up messages */}
      {isModalOpen && (
        <AddPlayListSongModal
          song={data}
          closeModal={() => SetIsModalOpen(false)}
          setSnackBar={setSnackBar}
        />
      )}
    </div>
  );
}
Example #9
Source File: index.js    From whaticket with MIT License 5 votes vote down vote up
MessageOptionsMenu = ({ message, menuOpen, handleClose, anchorEl }) => {
  const { setReplyingMessage } = useContext(ReplyMessageContext);
  const [confirmationOpen, setConfirmationOpen] = useState(false);

  const handleDeleteMessage = async () => {
    try {
      await api.delete(`/messages/${message.id}`);
    } catch (err) {
      toastError(err);
    }
  };

  const hanldeReplyMessage = () => {
    setReplyingMessage(message);
    handleClose();
  };

  const handleOpenConfirmationModal = (e) => {
    setConfirmationOpen(true);
    handleClose();
  };

  return (
    <>
      <ConfirmationModal
        title={i18n.t("messageOptionsMenu.confirmationModal.title")}
        open={confirmationOpen}
        onClose={setConfirmationOpen}
        onConfirm={handleDeleteMessage}
      >
        {i18n.t("messageOptionsMenu.confirmationModal.message")}
      </ConfirmationModal>
      <Menu
        anchorEl={anchorEl}
        getContentAnchorEl={null}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "right",
        }}
        open={menuOpen}
        onClose={handleClose}
      >
        {message.fromMe && (
          <MenuItem onClick={handleOpenConfirmationModal}>
            {i18n.t("messageOptionsMenu.delete")}
          </MenuItem>
        )}
        <MenuItem onClick={hanldeReplyMessage}>
          {i18n.t("messageOptionsMenu.reply")}
        </MenuItem>
      </Menu>
    </>
  );
}
Example #10
Source File: CategoryMenu.jsx    From covid-trials-dashboard with MIT License 5 votes vote down vote up
CategoryMenu = ({
  allOptions: options,
  selectedRoute,
  onChange,
}) => {
  const [anchorEl, setAnchorEl] = React.useState(null)
  const { t } = useTranslation('menu')
  const handleClick = event => {
    setAnchorEl(event.currentTarget)
  }
  const handleClose = () => {
    setAnchorEl(null)
  }
  const onClick = event => {
    onChange(event)
    handleClose()
  }
  return (
    <div>
      <Button
        aria-controls='category-menu'
        aria-haspopup='true'
        color='inherit'
        onClick={handleClick}
      >
        {typeof selectedRoute === 'string' ? selectedRoute : options[0].label}{' '}
        <ExpandMoreIcon />
      </Button>
      <Menu
        id='category-menu'
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >
        {options.map(option => (
          <StyledMenuItem
            key={option.label}
            onClick={() => onClick(option.label)}
            selected={option.label === selectedRoute}
          >
            <ListItemText primary={t(option.label)} />
          </StyledMenuItem>
        ))}
      </Menu>
    </div>
  )
}
Example #11
Source File: Navigators.js    From clone-instagram-ui with MIT License 5 votes vote down vote up
Navigators = ({ className, username, onNavigationClick }) => {
  const [anchorEl, setAnchorEl] = React.useState(null);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = (type) => {
    setAnchorEl(null);
    if (type === 'log-out') {
      removeUserInformation();
      window.location.reload();
    }
  };
  return (
    <Toolbar className={className}>
      {username && (
        <React.Fragment>
          <Link to={`/home`} className="navigation-link">
            <IconButton edge="start" color="inherit" aria-label="menu">
              <Home />
            </IconButton>
          </Link>
          <IconButton color="inherit" aria-label="menu">
            <FavoriteBorderOutlined />
          </IconButton>
          <IconButton
            onClick={onNavigationClick.bind(null, 'add-media')}
            color="inherit"
            aria-label="menu"
          >
            <Add />
          </IconButton>
          {/* <Link to={`/profile/${username}`} className="navigation-link"></Link> */}
          <IconButton
            color="inherit"
            aria-label="menu"
            aria-controls="simple-menu"
            aria-haspopup="true"
            onClick={handleClick}
          >
            <Profile username={username} />
          </IconButton>
          <Menu
            id="simple-menu"
            anchorEl={anchorEl}
            keepMounted
            open={Boolean(anchorEl)}
          >
            <Link to={`/profile/${username}`} className="navigation-link">
              <MenuItem onClick={handleClose.bind(null, 'profile')}>
                Profile
              </MenuItem>
            </Link>
            <MenuItem onClick={handleClose.bind(null, 'log-out')}>
              Logout
            </MenuItem>
          </Menu>
        </React.Fragment>
      )}
      {!username && (
        <Link to="/start">
          <span>Login / Signup</span>
        </Link>
      )}
    </Toolbar>
  );
}
Example #12
Source File: UserMenuMobile.js    From stack-underflow with MIT License 5 votes vote down vote up
MobileUserMenu = ({ user, logoutUser }) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const classes = useMenuStyles();

  const handleOpenMenu = (event) => {
    setAnchorEl(event.currentTarget);
  };

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

  const handleLogoutClick = () => {
    logoutUser();
    handleCloseMenu();
  };

  return (
    <div>
      {user ? (
        <IconButton onClick={handleOpenMenu} className={classes.userBtnMob}>
          <Avatar
            alt={user.username}
            src={`https://secure.gravatar.com/avatar/${user.id}?s=164&d=identicon`}
            className={classes.avatar}
          />
          <MoreVertIcon color="primary" />
        </IconButton>
      ) : (
        <IconButton
          onClick={handleOpenMenu}
          color="primary"
          className={classes.moreBtn}
        >
          <MoreVertIcon color="primary" />
        </IconButton>
      )}
      <Menu
        anchorEl={anchorEl}
        getContentAnchorEl={null}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
        keepMounted
        transformOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
        open={Boolean(anchorEl)}
        onClose={handleCloseMenu}
        marginThreshold={0}
        elevation={1}
      >
        {user ? (
          <div>
            <MenuItem
              component={RouterLink}
              to={`/user/${user.username}`}
              onClick={handleCloseMenu}
            >
              <AccountCircleIcon className={classes.menuIcon} />
              My Profile
            </MenuItem>
            <MenuItem onClick={handleLogoutClick}>
              <PowerSettingsNewIcon className={classes.menuIcon} />
              Logout: {user.username}
            </MenuItem>
          </div>
        ) : (
          <AuthFormModal buttonType="mobile" closeMenu={handleCloseMenu} />
        )}
      </Menu>
    </div>
  );
}
Example #13
Source File: WidgetView.js    From react-code-splitting-2021-04-26 with MIT License 5 votes vote down vote up
Widget = ({
  classes,
  children,
  title,
  noBodyPadding,
  bodyClass,
  className,
  disableWidgetMenu,
  ...props
}) => (
  <div className={classes.widgetWrapper}>
    <Paper className={classes.paper} classes={{ root: classes.widgetRoot }}>
      <div className={classes.widgetHeader}>
        {props.header ? (
          props.header
        ) : (
          <React.Fragment>
            <Typography variant="h5" color="textSecondary">
              {title}
            </Typography>
            {!disableWidgetMenu && (
              <IconButton
                color="primary"
                classes={{ root: classes.moreButton }}
                aria-owns="widget-menu"
                aria-haspopup="true"
                onClick={() => props.setMoreMenuOpen(true)}
                buttonRef={props.setMoreButtonRef}
              >
                <MoreIcon />
              </IconButton>
            )}
          </React.Fragment>
        )}
      </div>
      <div
        className={classnames(classes.widgetBody, {
          [classes.noPadding]: noBodyPadding,
          [bodyClass]: bodyClass
        })}
      >
        {children}
      </div>
    </Paper>
    <Menu
      id="widget-menu"
      open={props.isMoreMenuOpen}
      anchorEl={props.moreButtonRef}
      onClose={() => props.setMoreMenuOpen(false)}
      disableAutoFocusItem
    >
      <MenuItem>
        <Typography>Edit</Typography>
      </MenuItem>
      <MenuItem>
        <Typography>Copy</Typography>
      </MenuItem>
      <MenuItem>
        <Typography>Delete</Typography>
      </MenuItem>
      <MenuItem>
        <Typography>Print</Typography>
      </MenuItem>
    </Menu>
  </div>
)
Example #14
Source File: LeftMenu.js    From Codelabz with Apache License 2.0 5 votes vote down vote up
LeftMenu = ({ mode }) => {
  const permissions = useGetPermissions();
  const allowDashboard = useAllowDashboard();
  let { pathname: location } = useLocation();

  const [anchorEl, setAnchorEl] = React.useState(null);

  const useStyles = makeStyles((theme) => ({
    menu: {
      width: "100%",
      display: "flex",
      flexDirection: "row",
      [theme.breakpoints.down(767)]: {
        flexDirection: "column",
      },
      marginTop: theme.spacing(5),
      borderRadius: "10px",
    },
  }));
  const classes = useStyles();

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

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

  return (
    <React.Fragment>
      <IconButton onClick={handleClick}>
        <AppsIcon />
      </IconButton>
      <Menu
        id="simple-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
        className={classes.menu}
        elevation={1}
      >
        <MenuItem key="/tutorials">
          <NavLink to="/tutorials">Tutorials</NavLink>
        </MenuItem>
        {allowDashboard && (
          <MenuItem key="my-code-feed">
            <NavLink to="/dashboard/my_feed">My CodeFeed</NavLink>
          </MenuItem>
        )}
        {allowDashboard && permissions.length > 0 && (
          <MenuItem key="/organization">
            <NavLink to="/organization">Organizations</NavLink>
          </MenuItem>
        )}
      </Menu>
    </React.Fragment>
  );
}
Example #15
Source File: CourseSort.js    From course-manager with MIT License 5 votes vote down vote up
export default function ShopProductSort() {
  const [open, setOpen] = useState(null);

  const handleOpen = (event) => {
    setOpen(event.currentTarget);
  };

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

  return (
    <>
      <Button
        color="inherit"
        disableRipple
        onClick={handleOpen}
        endIcon={<Icon icon={open ? chevronUpFill : chevronDownFill} />}
      >
        Sort By:&nbsp;
        <Typography component="span" variant="subtitle2" sx={{ color: 'text.secondary' }}>
          Newest
        </Typography>
      </Button>
      <Menu
        keepMounted
        anchorEl={open}
        open={Boolean(open)}
        onClose={handleClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'right' }}
      >
        {SORT_BY_OPTIONS.map((option) => (
          <MenuItem
            key={option.value}
            selected={option.value === 'newest'}
            onClick={handleClose}
            sx={{ typography: 'body2' }}
          >
            {option.label}
          </MenuItem>
        ))}
      </Menu>
    </>
  );
}
Example #16
Source File: PlaylistItem.js    From qasong with ISC License 5 votes vote down vote up
function PlaylistItem({
  song,
  handleStopSong,
  nowPlaying,
  setNowPlaying,
  addSongToQueue,
}) {
  const currentlyPlaying = song.videoId === nowPlaying?.videoId;
  const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = React.useState(null);

  const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);

  const handleMobileMenuClose = (event) => {
    event.stopPropagation();
    setMobileMoreAnchorEl(null);
  };

  const handleMobileMenuOpen = (event) => {
    event.stopPropagation();
    setMobileMoreAnchorEl(event.currentTarget);
  };

  const mobileMenuId = "primary-search-account-menu-mobile";
  return (
    <ListItem key={song.videoId} selected={currentlyPlaying}>
      {currentlyPlaying && (
        <IconButton size="small" onClick={handleStopSong}>
          <StopIcon />
        </IconButton>
      )}
      <ListItemText primary={song.title} />
      <IconButton edge="end" size="small" onClick={handleMobileMenuOpen}>
        <MoreVertIcon />
      </IconButton>
      <Menu
        anchorEl={mobileMoreAnchorEl}
        anchorOrigin={{
          vertical: "top",
          horizontal: "right",
        }}
        id={mobileMenuId}
        keepMounted
        transformOrigin={{
          vertical: "top",
          horizontal: "right",
        }}
        open={isMobileMenuOpen}
        onClose={handleMobileMenuClose}
      >
        <MenuItem
          onClick={() => {
            setNowPlaying(song);
            handleMobileMenuClose();
          }}
        >
          <p>Play Song</p>
        </MenuItem>
        <MenuItem
          onClick={() => {
            addSongToQueue(song);
            handleMobileMenuClose();
          }}
        >
          <p>Queue Song</p>
        </MenuItem>
      </Menu>
    </ListItem>
  );
}
Example #17
Source File: ProfileMenu.js    From ehr with GNU Affero General Public License v3.0 5 votes vote down vote up
render() {
        const menuItems = this.getMenuItems();
        const { anchorEl } = this.state;
        const open = Boolean(anchorEl);

        return (
            <div className="profile-menu">
                <DropdownIcon
                    aria-label="more"
                    aria-controls="long-menu"
                    aria-haspopup="true"
                    onClick={this.handleClick}
                    disableRipple={true}
                    size="small"
                >
                    <ArrowDropDown />
                </DropdownIcon>
                <Menu
                    id="menu-items"
                    anchorEl={anchorEl}
                    keepMounted
                    open={open}
                    onClose={this.handleClose}
                    getContentAnchorEl={null}
                    anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
                    transformOrigin={{ vertical: 'top', horizontal: 'left' }}
                    style={{ marginTop: '9px' }}
                >
                    {menuItems}
                    <Box m={1}>
                        <Divider />
                    </Box>
                    <MenuItem className="menuItem" onClick={this.onImportDataMenuItemClick}>
                        <span className="menuItemIcon">{getIcon('CloudUploadOutlined')}</span>
                        <span className="menuItemLabel">Import Data</span>
                    </MenuItem>
                </Menu>
            </div>
        );
    }
Example #18
Source File: ListMenu.js    From TrelloClone with MIT License 5 votes vote down vote up
ListMenu = ({ listId }) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const dispatch = useDispatch();

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

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

  const archive = async () => {
    dispatch(archiveList(listId, true));
  };

  return (
    <div>
      <Button onClick={handleClick}>
        <MoreHorizIcon />
      </Button>
      <Menu
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >
        <MenuItem onClick={handleClose}>
          <MoreHorizIcon />
        </MenuItem>
        <MenuItem
          onClick={() => {
            archive();
            handleClose();
          }}
        >
          Archive This List
        </MenuItem>
        <MenuItem>
          <MoveList listId={listId} closeMenu={handleClose} />
        </MenuItem>
      </Menu>
    </div>
  );
}
Example #19
Source File: PostMenu.js    From social-media-strategy-fe with MIT License 5 votes vote down vote up
PostMenu = ({ post, setEditing }) => {
	const dispatch = useDispatch();
	const [modalOpen, setModalOpen] = useState(false);
	const [anchorEl, setAnchorEl] = useState(null);
	const isOpen = Boolean(anchorEl);

	const handleAnchorEl = (e) => {
		setAnchorEl(e.currentTarget);
	};

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

	const handleEdit = () => {
		setEditing();
	};

	const handleDeleteClick = () => {
		setModalOpen(true);
		handleClose();
	};

	const handleDeleteConfirmation = async () => {
		dispatch(deletePost(post));
		handleClose();
	};

	return (
		<>
			<Modal
				open={modalOpen}
				handleClose={() => setModalOpen(false)}
				title="Delete this post?"
				handleConfirmation={handleDeleteConfirmation}
			/>
			<IconButton
				aria-label="account of current user"
				aria-controls="menu-appbar"
				aria-haspopup="true"
				onClick={handleAnchorEl}
				color="inherit"
			>
				<MoreHorizIcon fontSize="small" />
			</IconButton>

			<Menu
				id="menu-appbar"
				anchorEl={anchorEl}
				getContentAnchorEl={null}
				anchorOrigin={{
					vertical: "bottom",
					horizontal: "right",
				}}
				keepMounted
				transformOrigin={{
					vertical: "top",
					horizontal: "right",
				}}
				open={isOpen}
				onClose={handleClose}
			>
				{!post.posted && (
					<MenuItem onClick={handleEdit}>
						<ListItemIcon>
							<EditIcon fontSize="small" />
						</ListItemIcon>
						<ListItemText primary="Edit" />
					</MenuItem>
				)}
				<MenuItem onClick={handleDeleteClick}>
					<ListItemIcon>
						<DeleteIcon fontSize="small" />
					</ListItemIcon>
					<ListItemText primary="Delete" />
				</MenuItem>
			</Menu>
		</>
	);
}
Example #20
Source File: MainMenu.js    From dipact with GNU General Public License v3.0 4 votes vote down vote up
render() {
		return (
			//Below typography is wonky due to limited title classes. I really shouldn't be doing it like this. - Joren
			<React.Fragment>
				<AppBar position="fixed">
					<Toolbar>
						<IconButton
							edge="start"
							onClick={this.openDrawer}
							color="secondary"
							style={{marginRight:"16px"}}
						>
							<MenuIcon />
						</IconButton>

						<Typography variant="h6" style={{ flexGrow: 1 }}>

							{this.state.activity == Start
								? "My Games"
								: this.state.activity == GameMasterStart
								? "My Managed Games"
								: this.state.activity == GameList
								? "Public Games"
								: ""} 
						
						</Typography>
						<IconButton
							edge="end"
							onClick={(ev) => {
								this.setState({
									menuAnchorEl: ev.currentTarget,
								});
							}}
							color="secondary"
						>
							<Avatar
								alt="test"
								src={Globals.user.Picture}
								style={{
									width: "32px",
									height: "32px",
									border: "1px solid #FDE2B5",
								}}
							/>
						</IconButton>
						<Menu
							anchorEl={this.state.menuAnchorEl}
							anchorOrigin={{
								vertical: "top",
								horizontal: "right",
							}}
							transformOrigin={{
								vertical: "top",
								horizontal: "right",
							}}
							onClose={(_) => {
								this.setState({ menuAnchorEl: null });
							}}
							open={!!this.state.menuAnchorEl}
						>
							<MenuItem key="email" style={{ fontWeight: "bold" }}>
								{Globals.user.Email}
							</MenuItem>
							<MenuItem
								key="stats"
								onClick={(_) => {
									this.setState({
										menuAnchorEl: null,
										statsDialogOpen: true,
									});
								}}
							>
								Player stats
							</MenuItem>

							<MenuItem key="logout" onClick={helpers.logout}>
								Logout
							</MenuItem>
						</Menu>
					</Toolbar>
				</AppBar>
				<div style={{ marginTop: "60px" }}>{this.renderActivity()}</div>
				<Drawer open={this.state.drawerOpen}>
					<ClickAwayListener
						onClickAway={(_) => {
							if (new Date().getTime() > this.drawerOpenedAt + 100) {
								this.closeDrawer();
							}
						}}
					>
						<div onClick={this.closeDrawer} style={{ width: "220px" }}>
							<List component="nav">
								<ListItem
									style={{
										padding: "24px 16px 8px 16px",
										height: "40px",
									}}
								>
									<ListItemText
										primary="My Diplicity"
										disableTypography
										style={{
											color: "rgba(40, 26, 26, 0.56)",
											minHeight: "auto",
											minWidth: "auto",
											font: "500 14px / 48px Cabin, Roboto, sans-serif",
											margin: "0px 0px 2px",
										}}
									/>
								</ListItem>

								<ListItem
									button
									onClick={(_) => {
										this.setActivity(Start, {
											urls: this.props.urls,
											findPrivateGame: this.findGameByID,
											findOpenGame: this.renderOpenGames,
											renderMyFinishedGames: this.renderMyFinishedGames,
										});
									}}
								>
									<ListItemText primary="My games" />
								</ListItem>

								<ListItem
									button
									onClick={(_) => {
										this.setActivity(GameMasterStart, {
											urls: this.props.urls,
											findPrivateGame: this.findGameByID,
											findOpenGame: this.renderOpenGames,
											renderMyFinishedGames: this.renderMyFinishedGames,
										});
									}}
								>
									<ListItemText primary="My managed games" />
								</ListItem>

								<ListItem
									button
									onClick={(_) => {
										this.setState({ menuAnchorEl: null });
										this.settingsDialog.setState({
											open: true,
										});
									}}
								>
									<ListItemText primary="Settings" />
								</ListItem>

								<Divider />

								<ListItem
									style={{
										padding: "24px 16px 8px 16px",
										height: "40px",
									}}
								>
									<ListItemText
										primary="Public games"
										disableTypography
										style={{
											color: "rgba(40, 26, 26, 0.56)",
											minHeight: "auto",
											minWidth: "auto",
											font: "500 14px / 48px Cabin, Roboto, sans-serif",
											margin: "0px 0px 2px",
										}}
									/>
								</ListItem>

								<ListItem
									button
									urlkey="open-games"
									label="Open games"
									onClick={this.renderGameList}
								>
									<ListItemText primary="Open to join" />
								</ListItem>
								<ListItem
									style={{ padding: "4px 16px" }}
									button
									urlkey="started-games"
									label="Started games"
									onClick={this.renderGameList}
								>
									<ListItemText primary="Started" />
								</ListItem>
								<ListItem
									button
									urlkey="finished-games"
									label="Finished games"
									onClick={this.renderGameList}
								>
									<ListItemText primary="Finished" />
								</ListItem>

								<Divider />

								<ListItem
									style={{
										padding: "24px 16px 8px 16px",
										height: "40px",
									}}
								>
									<ListItemText
										primary="Community"
										disableTypography
										style={{
											color: "rgba(40, 26, 26, 0.56)",
											minHeight: "auto",
											minWidth: "auto",
											font: "500 14px / 48px Cabin, Roboto, sans-serif",
											margin: "0px 0px 2px",
										}}
									/>
								</ListItem>

								<ListItem
									button
									onClick={(_) => {
										open("https://discord.gg/bu3JxYc");
									}}
								>
									<ListItemText primary="Chat" />
								</ListItem>

								<ListItem
									style={{ padding: "4px 16px" }}
									button
									onClick={(_) => {
										open("https://groups.google.com/g/diplicity-talk");
									}}
								>
									<ListItemText primary="Forum" />
								</ListItem>
								<Divider />
								<ListItem
									button
									onClick={(_) => {
										open(
											"https://diplicity.notion.site/diplicity/Diplicity-FAQ-7b4e0a119eb54c69b80b411f14d43bb9"
										);
									}}
								>
									<ListItemText primary="FAQ" />
								</ListItem>
								<ListItem
									button
									onClick={(_) => {
										this.setActivity(About);
									}}
								>
									<ListItemText primary="About" />
								</ListItem>
							</List>
							<div
								style={{
									width: "calc(100% - 16px)",
									display: "Flex",
									justifyContent: "space-around",
									padding: "0px 8px",
								}}
							>
								<div
									id="github"
									style={{ padding: "8px" }}
									onClick={(_) => {
										open("https://github.com/zond/dipact");
									}}
								>
									<GitHubIcon />
								</div>
								<div
									id="errorlog"
									style={{ padding: "8px" }}
									onClick={(_) => {
										this.errorsDialog.setState({
											open: true,
										});
									}}
								>
									<BugReportIcon />
								</div>
								<div
									id="donate"
									style={{ padding: "8px" }}
									onClick={(_) => {
										this.donateDialog.setState({
											open: true,
										});
									}}
								>
									<DonateIcon />
								</div>
							</div>
						</div>
					</ClickAwayListener>
				</Drawer>
				<FindGameDialog
					parentCB={(c) => {
						this.findGameDialog = c;
					}}
					key="find-game-dialog"
				/>
				<DonateDialog
					key="donate-dialog"
					parentCB={(c) => {
						this.donateDialog = c;
					}}
				/>
				<SettingsDialog
					key="settings-dialog"
					parentCB={(c) => {
						this.settingsDialog = c;
					}}
				/>
				<ErrorsDialog
					key="errors-dialog"
					parentCB={(c) => {
						this.errorsDialog = c;
					}}
				/>
				{this.state.statsDialogOpen ? (
					<StatsDialog
						open={this.state.statsDialogOpen}
						user={Globals.user}
						onClose={(_) => {
							this.setState({ statsDialogOpen: false });
						}}
					/>
				) : (
					""
				)}
			</React.Fragment>
		);
	}
Example #21
Source File: Menu.js    From qasong with ISC License 4 votes vote down vote up
function MobileMenu({ queueLength, setShowAboutUs, setShowSettings, setShowFeedback }) {
  const classes = useStyles();

  let history = useHistory();

  const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = React.useState(null);

  const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);

  const handleMobileMenuClose = () => {
    setMobileMoreAnchorEl(null);
  };

  const handleMobileMenuOpen = (event) => {
    setMobileMoreAnchorEl(event.currentTarget);
  };

  function handleQueueButtonClick() {
    history.push("/queue");
    handleMobileMenuClose();
  }

  function handleBillboardClick() {
    history.push("/billboard");
    handleMobileMenuClose();
  }

  function handlePlaylistClick() {
    history.push("/playlists");
    handleMobileMenuClose();
  }

  function handleSettingsClick() {
    setShowSettings(true);
    history.push("/");
  }

  function handleAboutUsClick() {
    setShowAboutUs(true);
    history.push("/");
  }

  function handleFeedbackClick() {
    setShowFeedback(true);
    history.push("/");
    handleMobileMenuClose();
  }

  const mobileMenuId = "primary-search-account-menu-mobile";
  return (
    <div>
      <Menu
        anchorEl={mobileMoreAnchorEl}
        anchorOrigin={{
          vertical: "top",
          horizontal: "right",
        }}
        id={mobileMenuId}
        keepMounted
        transformOrigin={{
          vertical: "top",
          horizontal: "right",
        }}
        open={isMobileMenuOpen}
        onClose={handleMobileMenuClose}
        className={classes.backdrop}
      >
        {/* QUEUE */}

        <MenuItem onClick={handleQueueButtonClick}>
          queue
          <IconButton target="_blank" color="inherit" size="small">
            <Badge badgeContent={queueLength} color="secondary">
              <QueueMusicIcon />
            </Badge>
          </IconButton>
        </MenuItem>
        <MenuItem onClick={handlePlaylistClick}>playlists</MenuItem>
        <MenuItem onClick={handleBillboardClick}>billboard top 100</MenuItem>
        <MenuItem onClick={handleSettingsClick}>settings</MenuItem>
        <MenuItem onClick={handleFeedbackClick}>feedback</MenuItem>
        <MenuItem onClick={handleAboutUsClick}>about us</MenuItem>
      </Menu>

      <IconButton
        aria-label="show more"
        aria-controls={mobileMenuId}
        aria-haspopup="true"
        onClick={handleMobileMenuOpen}
        color="inherit"
      >
        <Badge badgeContent={queueLength} color="secondary">
          <MoreIcon style={{ fontSize: 36 }} />
        </Badge>
      </IconButton>
    </div>
  );
}
Example #22
Source File: Game.js    From dipact with GNU General Public License v3.0 4 votes vote down vote up
render() {
		if (this.state.game) {
			return (
				<React.Fragment>
					<AppBar
						key="app-bar"
						position="fixed"
						color={this.state.laboratoryMode ? "secondary" : "primary"}
					>
						<Toolbar>
							{!this.state.laboratoryMode ? (
								<IconButton
									onClick={this.props.close}
									key="close"
									edge="start"
									color="secondary"
								>
									<CloseIcon />
								</IconButton>
							) : (
								<IconButton
									onClick={(_) => {
										this.setState(
											{
												moreMenuAnchorEl: null,
												laboratoryMode: !this.state.laboratoryMode,
											},
											(_) => {
												if (!this.state.laboratoryMode) {
													this.loadGame();
												} else {
													gtag("event", "enable_lab_mode");
												}
											}
										);
									}}
									key="close"
									edge="start"
									color="primary"
								>
									<CloseIcon />
								</IconButton>
							)}
							{!this.state.laboratoryMode &&
							this.state.activePhase &&
							this.state.activePhase.Properties.PhaseOrdinal > 1 ? (
								<IconButton
									onClick={this.phaseJumper(-1)}
									key="previous"
									edge="start"
									color="secondary"
								>
									<PreviousIcon />
								</IconButton>
							) : !this.state.laboratoryMode ? (
								<Box key="prev-spacer"></Box>
							) : (
								""
							)}

							{this.state.laboratoryMode ? (
								<Typography variant="h6" style={{ marginRight: "8px" }}>
									Sandbox
								</Typography>
							) : (
								""
							)}
							{this.state.activePhase ? (
								<Select
									/* TODO: This might be a stretch, but Laboratory mode has SOME "real" and some "fake" turns. E.g. in spring 1902 I can move back to Spring 1901 and create an "alternative" 1901 and commit that. 
                  Is it possible to make all the "hypothetical" phases to change color? Maybe let me know in the Discord chat and we can discuss more. */
									/*
									 * Yes it is - 'real' phases have .Properties.ID, while fake phases don't (IIRC).
									 */
									style={
										this.state.laboratoryMode
											? {
													width: "100%",
													minWidth: "0",
													borderBottom: "1px solid rgba(253, 226, 181, 0.7)",
													color: "rgb(40, 26, 26)",
											  }
											: {
													width: "100%",
													minWidth: "0",
													borderBottom: "1px solid rgba(253, 226, 181, 0.7)",
													color: "#FDE2B5",
											  }
									}
									key="phase-select"
									value={this.state.activePhase.Properties.PhaseOrdinal}
									onChange={this.changePhase}
									label={helpers.phaseName(this.state.activePhase)}
								>
									{this.state.phases.map((phase) => {
										return (
											<MenuItem
												key={phase.Properties.PhaseOrdinal}
												style={{
													textOverflow: "ellipsis",
												}}
												value={phase.Properties.PhaseOrdinal}
											>
												{helpers.phaseName(phase)}
												{!this.state.game.Properties.Started ||
												phase.Properties.Resolved ? (
													""
												) : (
													<span
														dataat={
															new Date().getTime() +
															phase.Properties.NextDeadlineIn * 1e-6
														}
														style={{
															position: "relative",
															top: "-6px",
															fontSize: "xx-small",
															left: "-5px",
															zIndex: "1",
															backgroundColor: "red",
															borderRadius: "7px",
															padding: "0 2px 1px 2px",
														}}
													>
														{helpers.minutesToDuration(
															(phase.Properties.NextDeadlineIn * 1e-9) / 60.0,
															true
														)}
													</span>
												)}
											</MenuItem>
										);
									})}
								</Select>
							) : !this.state.laboratoryMode ? (
								<Box key="curr-spacer" width="100%"></Box>
							) : (
								""
							)}
							{this.state.activePhase &&
							this.state.activePhase.Properties.PhaseOrdinal <
								this.state.phases[this.state.phases.length - 1].Properties
									.PhaseOrdinal ? (
								<IconButton
									onClick={this.phaseJumper(1)}
									edge="end"
									key="next"
									color="secondary"
								>
									<NextIcon />
								</IconButton>
							) : !this.state.laboratoryMode ? (
								<Box key="next-spacer"></Box>
							) : (
								""
							)}

							{!this.state.laboratoryMode ? (
								<IconButton
									edge="end"
									key="more-icon"
									color="secondary"
									onClick={(ev) => {
										this.setState({
											moreMenuAnchorEl: ev.currentTarget,
										});
									}}
								>
									<SettingsIcon />
								</IconButton>
							) : (
								""
							)}
							<Menu
								anchorEl={this.state.moreMenuAnchorEl}
								anchorOrigin={{
									vertical: "top",
									horizontal: "right",
								}}
								transformOrigin={{
									vertical: "top",
									horizontal: "right",
								}}
								onClose={(_) => {
									this.setState({ moreMenuAnchorEl: null });
								}}
								open={!!this.state.moreMenuAnchorEl}
							>
								<MenuItem
									key="game-metadata"
									onClick={(_) => {
										this.setState({
											moreMenuAnchorEl: null,
										});
										if (this.state.game.Properties.Started) {
											this.gamePlayersDialog.setState({
												open: true,
											});
										} else {
											this.metadataDialog.setState({
												open: true,
											});
										}
									}}
								>
									Game & player info
								</MenuItem>
								{this.state.game.Properties.Started
									? [
											<MenuItem
												key="scores"
												onClick={(_) => {
													this.setState({
														moreMenuAnchorEl: null,
													});
													this.preliminaryScores.setState({
														open: true,
													});
												}}
											>
												Scores
											</MenuItem>,
											this.state.game.Properties.Finished ? (
												<MenuItem
													key="results"
													onClick={(_) => {
														this.setState({
															moreMenuAnchorEl: null,
														});
														this.gameResults.setState({
															open: true,
														});
													}}
												>
													Results
												</MenuItem>
											) : (
												""
											),
									  ]
									: ""}
								<Divider />
								<MenuItem key="game-id" onClick={this.shareNative}>
									{this.state.game.Properties.Started
										? "Share game"
										: "Invite players"}
								</MenuItem>

								<MenuItem
									key="download-map"
									onClick={(_) => {
										this.setState({
											moreMenuAnchorEl: null,
										});
										this.dip_map.downloadMap();
										gtag("event", "download_map");
									}}
								>
									Download map
								</MenuItem>
								<MenuItem
									key="laboratory-mode"
									onClick={(_) => {
										this.setState(
											{
												moreMenuAnchorEl: null,
												laboratoryMode: !this.state.laboratoryMode,
											},
											(_) => {
												if (!this.state.laboratoryMode) {
													this.loadGame();
												} else {
													gtag("event", "enable_lab_mode");
												}
											}
										);
									}}
								>
									{this.state.laboratoryMode
										? "Turn off sandbox mode"
										: "Sandbox mode"}
								</MenuItem>
								<Divider />
								<MenuItem
									key="How to play"
									onClick={(_) => {
										window.open(
											"https://diplicity.notion.site/How-to-play-39fbc4d1f1924c928c3953095062a983",
											"_blank"
										);
									}}
								>
									How to play
								</MenuItem>
								<MenuItem
									key="debug-data"
									onClick={(_) => {
										helpers
											.copyToClipboard(JSON.stringify(this.debugCounters))
											.then((_) => {
												this.setState({
													moreMenuAnchorEl: null,
												});
												helpers.snackbar("Debug data copied to clipboard");
											});
									}}
								>
									Debug
								</MenuItem>
							</Menu>
							{this.state.laboratoryMode ? (
								<React.Fragment>
									<IconButton
										onClick={(_) => {
											this.dip_map.downloadMap();
											gtag("event", "download_map");
										}}
										color="primary"
										edge="end"
										style={{ marginLeft: "auto" }}
									>
										<DownloadIcon />
									</IconButton>
									<IconButton
										onClick={(_) => {
											this.dip_map.labShare();
										}}
										color="primary"
										edge="end"
										style={{ marginLeft: "auto" }}
									>
										<ShareIcon />
									</IconButton>
								</React.Fragment>
							) : (
								""
							)}
						</Toolbar>
						{!this.state.laboratoryMode ? (
							<React.Fragment>
								{!this.state.game.Properties.Started ||
								this.state.game.Links.find((l) => {
									return l.Rel === "join";
								}) ? (
									<Toolbar
										style={{
											display: "flex",
											justifyContent: "space-between",
											minHeight: "53px",
										}}
									>
										<div>
											{this.state.game.Links.find((l) => {
												return l.Rel === "join";
											}) ? (
												<Button
													variant="outlined"
													color="secondary"
													key="join"
													onClick={this.join}
												>
													Join
												</Button>
											) : (
												""
											)}
											{this.state.game.Links.find((l) => {
												return l.Rel === "leave";
											}) ? (
												<Button
													variant="outlined"
													color="secondary"
													key="leave"
													onClick={this.leave}
												>
													Leave
												</Button>
											) : (
												""
											)}
										</div>
										<div
											style={{
												display: "flex",
												alignItems: "center",
											}}
										>
											<NumMembersIcon />{" "}
											<Typography
											//TODO: Change this to not NMembers but Nmembers - replaceable.
												variant="body2"
												style={{ paddingLeft: "2px" }}
											>
												{this.state.game.Properties.NMembers}/
												{this.state.variant.Properties.Nations.length}{" "}
											</Typography>
										</div>
									</Toolbar>
								) : (
									""
								)}
								<Tabs
									key="tabs"
									value={this.state.activeTab}
									onChange={this.changeTab}
									display="flex"
									variant="fullWidth"
								>
									<Tab value="map" icon={<MapIcon />} />
									<Tab
										value="chat"
										icon={
											this.state.member && this.state.unreadMessages > 0 ? (
												<Badge badgeContent={this.state.unreadMessages}>
													<ChatIcon />
												</Badge>
											) : (
												<ChatIcon />
											)
										}
									/>
									{this.state.game.Properties.Started ? (
										this.state.member &&
										!this.state.activePhase.Properties.Resolved ? (
											this.state.member.NewestPhaseState.OnProbation ||
											!this.state.member.NewestPhaseState.ReadyToResolve ? (
												<Tab
													value="orders"
													icon={
														<SvgIcon>
															<path
																d="M9,0 C10.3,0 11.4,0.84 11.82,2 L11.82,2 L16,2 C17.1045695,2 18,2.8954305 18,4 L18,4 L18,18 C18,19.1045695 17.1045695,20 16,20 L16,20 L2,20 C0.8954305,20 0,19.1045695 0,18 L0,18 L0,4 C0,2.8954305 0.8954305,2 2,2 L2,2 L6.18,2 C6.6,0.84 7.7,0 9,0 Z M5,14 L3,14 L3,16 L5,16 L5,14 Z M15,14 L7,14 L7,16 L15,16 L15,14 Z M5,6 L3,6 L3,12 L5,12 L5,6 Z M15,10 L7,10 L7,12 L15,12 L15,10 Z M15,6 L7,6 L7,8 L15,8 L15,6 Z M9,2 C8.44771525,2 8,2.44771525 8,3 C8,3.55228475 8.44771525,4 9,4 C9.55228475,4 10,3.55228475 10,3 C10,2.44771525 9.55228475,2 9,2 Z"
																id="order_open"
															></path>
														</SvgIcon>
													}
												/>
											) : (
												<Tab
													value="orders"
													icon={
														<SvgIcon>
															<path
																d="M9,0 C10.3,0 11.4,0.84 11.82,2 L11.82,2 L16,2 C17.1045695,2 18,2.8954305 18,4 L18,4 L18,18 C18,19.1045695 17.1045695,20 16,20 L16,20 L2,20 C0.8954305,20 0,19.1045695 0,18 L0,18 L0,4 C0,2.8954305 0.8954305,2 2,2 L2,2 L6.18,2 C6.6,0.84 7.7,0 9,0 Z M13.4347826,7 L7.70608696,12.7391304 L4.56521739,9.60869565 L3,11.173913 L7.70608696,15.8695652 L15,8.56521739 L13.4347826,7 Z M9,2 C8.44771525,2 8,2.44771525 8,3 C8,3.55228475 8.44771525,4 9,4 C9.55228475,4 10,3.55228475 10,3 C10,2.44771525 9.55228475,2 9,2 Z"
																id="order_confirmed"
															></path>
														</SvgIcon>
													}
												/>
											)
										) : (
											<Tab value="orders" icon={<EventIcon />} />
										)
									) : (
										""
									)}
								</Tabs>
							</React.Fragment>
						) : (
							<Toolbar>
								<Typography variant="body1" style={{ marginRight: "8px" }}>
									Edit
								</Typography>
								<FormControlLabel
									key="edit-mode"
									control={
										<Switch
											onChange={(ev) => {
												this.setState({
													labEditMode: !ev.target.checked,
												});
												this.dip_map.setState({
													labEditMode: !ev.target.checked,
												});
											}}
											color="primary"
											checked={!this.state.labEditMode}
										/>
									}
									label="Play as"
								/>
								{!this.state.labEditMode ? (
									<FormControl
										key="play-as"
										style={{
											flexGrow: 1,
										}}
									>
										<Select
											value={this.state.labPlayAs}
											onChange={(ev) => {
												this.setState({
													labPlayAs: ev.target.value,
												});
												this.dip_map.setState({
													labPlayAs: ev.target.value,
												});
											}}
											style={{
												width: "100%",
												minWidth: "0",
												borderBottom: "1px solid rgba(253, 226, 181, 0.7)",
												color: "rgb(40, 26, 26)",
											}}
										>
											{this.state.variant.Properties.Nations.map((nation) => {
												return (
													<MenuItem key={nation} value={nation}>
														{nation}
													</MenuItem>
												);
											})}
										</Select>
									</FormControl>
								) : (
									""
								)}

								<IconButton
									edge="end"
									onClick={(ev) => {
										this.dip_map.labResolve();
									}}
									style={{
										marginLeft: "auto",
										color: "rgb(40, 26, 26)",
									}}
								>
									<FastForwardIcon />
								</IconButton>
							</Toolbar>
						)}
					</AppBar>

					<div
						key="map-container"
						style={
							this.state.laboratoryMode
								? {
										marginTop: "" + this.state.marginTop + "px",
										height: "calc(100% - " + this.state.marginTop + "px)",
										backgroundColor: "black",
										display: this.state.activeTab === "map" ? "block" : "none",
								  }
								: {
										marginTop: "" + this.state.marginTop + "px",
										height: "calc(100% - " + this.state.marginTop + "px)",
										backgroundColor: "black",
										display: this.state.activeTab === "map" ? "block" : "none",
								  }
						}
					>
						<DipMap
							parentCB={(c) => {
								this.dip_map = c;
							}}
							onLeaveProbation={(_) => {
								this.loadGame();
							}}
							debugCount={this.debugCount}
							labPhaseResolve={this.labPhaseResolve}
							serializePhaseState={this.serializePhaseState}
							laboratoryMode={this.state.laboratoryMode}
							isActive={this.state.activeTab === "map"}
							game={this.state.game}
							phase={this.state.activePhase}
							corroborateSubscriber={this.receiveCorroboration}
							variant={this.state.variant}
						/>
					</div>
					<React.Fragment>
						<div
							key="chat-container"
							style={{
								marginTop: "" + this.state.marginTop + "px",
								height: "calc(100% - " + this.state.marginTop + "px)",
								display: this.state.activeTab === "chat" ? "block" : "none",
							}}
						>
							<ChatMenu
								onNewGameState={this.onNewGameState}
								gameState={
									this.state.member && this.state.gameStates
										? this.state.gameStates.find((gs) => {
												return (
													gs.Properties.Nation === this.state.member.Nation
												);
										  })
										: null
								}
								isActive={this.state.activeTab === "chat"}
								unreadMessages={this.setUnreadMessages}
								phases={this.state.phases}
								game={this.state.game}
								parent={this}
							/>
						</div>
						{this.state.game.Properties.Started ? (
							<div
								key="orders-container"
								style={{
									marginTop: "" + this.state.marginTop + "px",
									height: "calc(100% - " + this.state.marginTop + "px)",
									display: this.state.activeTab === "orders" ? "flex" : "none",
									flexDirection: "column",
									justifyContent: "space-between",
								}}
							>
								<OrderList
									isActive={this.state.activeTab === "orders"}
									member={this.state.member}
									phase={this.state.activePhase}
									corroboration={this.state.corroboration}
									newPhaseStateHandler={(phaseState) => {
										this.setState((state, props) => {
											state = Object.assign({}, state);
											state.member.NewestPhaseState = phaseState.Properties;
											return state;
										});
										if (this.props.onChangeReady) {
											this.props.onChangeReady();
										}
									}}
									variant={this.state.variant}
								/>
							</div>
						) : (
							""
						)}
						<GamePlayers
							gameStates={this.state.gameStates}
							game={this.state.game}
							variant={this.state.variant}
							onNewGameState={this.onNewGameState}
							parentCB={(c) => {
								this.gamePlayersDialog = c;
							}}
						/>
						<PreliminaryScores
							phases={this.state.phases}
							variant={this.state.variant}
							parentCB={(c) => {
								this.preliminaryScores = c;
							}}
						/>
					</React.Fragment>
					{!this.state.game.Properties.Started ? (
						<React.Fragment>
							<NationPreferencesDialog
								parentCB={(c) => {
									this.nationPreferencesDialog = c;
								}}
								onSelected={null}
							/>
							<MetadataDialog
								game={this.state.game}
								parentCB={(c) => {
									this.metadataDialog = c;
								}}
							/>
						</React.Fragment>
					) : (
						""
					)}
					{!this.state.member ||
					!this.state.game.Properties.Started ||
					this.state.game.Properties.Mustered ? (
						""
					) : (
						<MusteringPopup
							viewOrders={(_) => {
								this.setState({
									activeTab: "orders",
									readyReminder: false,
								});
							}}
						/>
					)}
					<GameResults
						onNewGameState={this.onNewGameState}
						gameState={
							this.state.member && this.state.gameStates
								? this.state.gameStates.find((gs) => {
										return gs.Properties.Nation === this.state.member.Nation;
								  })
								: null
						}
						game={this.state.game}
						variant={this.state.variant}
						parentCB={(c) => {
							this.gameResults = c;
						}}
					/>
					<Snackbar
						anchorOrigin={{
							vertical: "bottom",
							horizontal: "center",
						}}
						open={this.state.readyReminder}
						autoHideDuration={30000}
						onClose={(_) => {
							this.setState({ readyReminder: false });
						}}
						message={[
							<Typography key="ready-warning">
								You haven't confirmed your orders yet.
								{this.state.game.Properties.Mustered
									? ""
									: " For the game to start, all players have to confirm as ready to play."}
							</Typography>,
						].concat(
							this.state.phaseMessages.map((m) => {
								return <Typography key={m}>{m}</Typography>;
							})
						)}
						action={
							<React.Fragment>
								<Button
									color="secondary"
									size="small"
									onClick={(_) => {
										this.setState({
											activeTab: "orders",
											readyReminder: false,
										});
									}}
								>
									View orders
								</Button>
								<IconButton
									size="small"
									aria-label="close"
									color="inherit"
									onClick={(_) => {
										this.setState({ readyReminder: false });
									}}
								>
									<CloseIcon />
								</IconButton>
							</React.Fragment>
						}
					/>
				</React.Fragment>
			);
		} else {
			return "";
		}
	}
Example #23
Source File: ShareButton.js    From warsinhk with MIT License 4 votes vote down vote up
function ShareButton(props) {
  const [anchorEl, setAnchorEl] = React.useState(null)
  const { site } = useStaticQuery(
    graphql`
      query {
        site {
          siteMetadata {
            siteUrl
          }
        }
      }
    `
  )

  function getPageUrl() {
    let url = `${site.siteMetadata.siteUrl}${fullPath}`

    if (props.caseId) {
      url = `${site.siteMetadata.siteUrl}${fullPath}/${props.caseId}`
    }

    if (!isSSR()) {
      url = url + decodeURIComponent(window.location.hash)
    }

    return url
  }

  function handleShareButtonClick(event) {
    if (!isSSR() && isWebShareAPISupported()) {
      const data = getWebShareData(getPageUrl())
      if (navigator.canShare(data)) {
        navigator.share(data).then(() => {
          trackCustomEvent({
            category: "general",
            action: "click",
            label: "share",
          })
        })

        return
      }
    }

    setAnchorEl(event.currentTarget)
  }

  function handleShareButtonClose(media) {
    setAnchorEl(null)
    if (typeof media === "string") {
      trackCustomEvent({
        category: "general",
        action: "click",
        label: `share_${media}`,
      })
    }
  }
  const { pathname: fullPath } = useLocation()

  const url = getPageUrl()

  return (
    <>
      <StyledIconButton
        color="inherit"
        aria-label="Share"
        aria-controls="share-menu"
        aria-haspopup="true"
        onClick={handleShareButtonClick}
      >
        <ShareIcon />
      </StyledIconButton>
      <Menu
        id="share-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleShareButtonClose}
      >
        <MenuItem onClick={() => handleShareButtonClose("facebook")}>
          <FacebookShareButton
            url={getShareUrl(url, "facebook")}
            children={<FacebookIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("telegram")}>
          <TelegramShareButton
            url={getShareUrl(url, "telegram")}
            children={<TelegramIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("whatsapp")}>
          <WhatsappShareButton
            url={getShareUrl(url, "whatsapp")}
            children={<WhatsappIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("twitter")}>
          <TwitterShareButton
            url={getShareUrl(url, "twitter")}
            children={<TwitterIcon size={32} round={true} />}
          />
        </MenuItem>
        <MenuItem onClick={() => handleShareButtonClose("link")}>
          <StyledCopyIcon
            onClick={() => {
              navigator.clipboard.writeText(url)
            }}
          />
        </MenuItem>
      </Menu>
    </>
  )
}
Example #24
Source File: Navbar.js    From Octave with MIT License 4 votes vote down vote up
function Navbar() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const [anchorEl, setAnchorEl] = useState(null);
  const [currentLocation, setCurrentLocation] = useState("/");
  const user = useSelector((state) => state.user);

  useEffect(() => {
    setCurrentLocation(location.pathname);
  }, [location.pathname]);

  // useEffect(() => {
  //   let unlisten = history.listen((location) => {
  //     setCurrentLocation(location.pathname);
  //   });
  //   return unlisten;
  // }, [history]);

  const openOptions = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const logout = async () => {
    try {
      await signOut();
      dispatch(logoutUser());
      navigate("/");
    } catch (error) {
      alert(error.message);
    }
  };

  return (
    <div className="navbar">
      <img
        className="navbar__logo"
        src="https://raw.githubusercontent.com/mani-barathi/mani-barathi.github.io/master/assets/favicon.ico"
        alt=""
        onDoubleClick={() => navigate("/admin")}
      />

      <div className="navbar__center">
        <Link
          to="/"
          className={
            currentLocation === "/"
              ? `navbar__link navbar__link--active`
              : "navbar__link"
          }
        >
          <span className="navbar__linkSpan">Home</span>
          <span className="navbar__linkIcon">
            <HomeIcon />
          </span>
        </Link>
        <Link
          to="/library"
          className={
            currentLocation === "/library"
              ? `navbar__link navbar__link--active`
              : "navbar__link"
          }
        >
          <span className="navbar__linkSpan">Library</span>
          <span className="navbar__linkIcon">
            <LibraryMusicIcon />
          </span>
        </Link>
        <Link
          to="/search"
          className={
            currentLocation === "/search"
              ? `navbar__link navbar__link--active`
              : "navbar__link"
          }
        >
          <span className="navbar__linkIcon">
            <SearchIcon />
          </span>
          <span className="navbar__linkSpan">Search</span>
        </Link>
      </div>

      <div className="navbar__right">
        <IconButton
          className="song__optionIcon"
          aria-controls="simple-menu"
          aria-haspopup="true"
          onClick={openOptions}
        >
          <Avatar src={user.photoURL} className="navbar__avatar">
            {" "}
          </Avatar>
        </IconButton>
        <Menu
          elevation={0}
          getContentAnchorEl={null}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "center",
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "center",
          }}
          id="simple-menu"
          anchorEl={anchorEl}
          keepMounted
          open={Boolean(anchorEl)}
          onClose={() => setAnchorEl(false)}
        >
          <MenuItem onClick={logout}>
            <ExitToAppIcon fontSize="small" />
            <span className="navbar__rightMenuItem">Logout</span>
          </MenuItem>
        </Menu>
      </div>
    </div>
  );
}
Example #25
Source File: Tree.js    From verapdf-webapp-gui with GNU General Public License v3.0 4 votes vote down vote up
function Tree({ ruleSummaries, selectedCheck, setSelectedCheck, errorsMap }) {
    const [language, setLanguage] = useState(getItem(LS_ERROR_MESSAGES_LANGUAGE) || languageEnum.English);
    const [anchorMenuEl, setAnchorMenuEl] = useState(null);
    const [expandedRule, setExpandedRule] = useState(UNSELECTED);
    const onRuleClick = useCallback(
        index => {
            if (expandedRule === index) {
                return setExpandedRule(UNSELECTED);
            }

            return setExpandedRule(index);
        },
        [expandedRule]
    );
    const onCheckClick = useCallback(checkKey => setSelectedCheck(checkKey), [setSelectedCheck]);

    // info dialog props
    const [openedRule, setOpenedRule] = useState(UNSELECTED);
    const [infoDialogOpened, setInfoDialogOpened] = useState(false);
    const onInfoClick = useCallback(rule => {
        setOpenedRule(rule);
        setInfoDialogOpened(true);
    }, []);
    const onInfoDialogClose = useCallback(() => {
        setInfoDialogOpened(false);
    }, []);
    const handleLanguageClick = useCallback(event => {
        setAnchorMenuEl(event.currentTarget);
    }, []);
    const handleLanguageClose = useCallback((language = null) => {
        if (language) {
            setItem(LS_ERROR_MESSAGES_LANGUAGE, language);
            setLanguage(language);
        }
        setAnchorMenuEl(null);
    }, []);

    useEffect(
        useCallback(() => {
            if (selectedCheck) {
                let [ruleIndex] = selectedCheck.split(':');
                ruleIndex = parseInt(ruleIndex);
                if (ruleIndex !== expandedRule) {
                    setExpandedRule(ruleIndex);
                }
            }
        }, [expandedRule, selectedCheck]),
        [selectedCheck]
    );

    return (
        <section className="summary-tree">
            <List
                className="summary-tree__list"
                aria-labelledby="summary-tree-subheader"
                subheader={
                    <ListSubheader component="div" id="summary-tree-subheader" disableSticky>
                        {LIST_HEADER}
                        <Tooltip title={language}>
                            <IconButton size="small" onClick={handleLanguageClick}>
                                <LanguageIcon />
                            </IconButton>
                        </Tooltip>
                        <Menu
                            id="language-menu"
                            anchorEl={anchorMenuEl}
                            keepMounted
                            open={Boolean(anchorMenuEl)}
                            onClose={handleLanguageClose.bind(this, undefined)}
                        >
                            {_.keys(languageEnum).map(lKey => (
                                <MenuItem key={lKey} onClick={handleLanguageClose.bind(this, languageEnum[lKey])}>
                                    {languageEnum[lKey]}
                                </MenuItem>
                            ))}
                        </Menu>
                    </ListSubheader>
                }
            >
                <RuleList
                    ruleSummaries={ruleSummaries}
                    expandedRule={expandedRule}
                    selectedCheck={selectedCheck}
                    onRuleClick={onRuleClick}
                    onCheckClick={onCheckClick}
                    onInfoClick={onInfoClick}
                    errorsMap={errorsMap}
                    errorMessages={errorMessages[language]}
                />
            </List>
            {openedRule !== UNSELECTED && (
                <InfoDialog
                    title={getRuleTitle(openedRule, errorMessages[language])}
                    open={infoDialogOpened}
                    onClose={onInfoDialogClose}
                >
                    {getRuleDescription(openedRule, errorMessages[language])}
                    <RuleDetailsButton rule={openedRule} errorMessages={errorMessages[language]} />
                </InfoDialog>
            )}
        </section>
    );
}
Example #26
Source File: Map.js    From pwa with MIT License 4 votes vote down vote up
function Map() {
    // FIXME you are using leaflet but you haven't imported it in this component because you have put it in index.html
    // try to use react leaflet and help encapsulation components (and Separation of concerns)

    const [chosenMap, setChosenMap] = useState(null);
    const [map, setMap] = useState(null);
    const [data, setData] = useState([]);
    const [label, setLabel] = useState([]);
    const [zoom, setZoom] = useState(0);
    const [anchorEl, setAnchorEl] = useState(null);
    const [isDataFetching, setIsDataFetching] = useState(false);
    const [isDataProcessing, setisDataProcessing] = useState(false);
    const [vpnAlert, setVpnAlert] = useState(true);

    const {user, token} = useSelector((state) => state.MyActivities);

    const {
        isMapFetching,
        isPrivateMapFetching,
        mapList,
        serverError,
    } = useSelector((state) => state.Map);
    const dispatch = useDispatch();

    const drawPolygon = useCallback(
        (color, polygons) => {
            if (map && polygons) {
                for (let polygon of polygons) {
                    let tooltip = null;
                    let width = null;
                    if (isNaN(polygon[polygon.length - 1][0])) {
                        tooltip = polygon[polygon.length - 1][0];
                        width = polygon[polygon.length - 1][1];
                        polygon = polygon.slice(0, polygon.length - 1);
                    }
                    window.L.polygon([polygon], {
                        fillColor: `#${(Number(color) % 0x1000000).toString(16)}`,
                        fill: true,
                        stroke: false,
                        fillOpacity: Number(color) / 0x1000000 / 255.0,
                    }).on('click', function (e) {
                        showTooltip(tooltip, width, e)
                    }).addTo(map);
                }
            }
        },
        [map]
    );

    var popup = map && window.L.popup();

    function showTooltip(tooltip, width, e) {
        if (tooltip !== null) {
            let url = `${process.env.REACT_APP_MAP_IMAGE_CDN}${tooltip}`;
            popup
                .setLatLng(e.latlng)
                .setContent("<div>" +
                    "<img style=\"max-width: 1000px; width: " + width + "px;\" alt=\"stats\" src=" + url + " /> </div>")
                .openOn(map);
        }
    }


    const clearPolygon = useCallback(() => {
        if (map) {
            d3.selectAll('.leaflet-interactive').remove();
        }
    }, [map]);

    const clearLabel = useCallback(() => {
        if (map) {
            d3.selectAll('.leaflet-tooltip').remove();
        }
    }, [map]);

    const getData = (url, result, cached = false) => {
        setIsDataFetching(false);

        if (!result) return undefined;

        // Add to cache if map does not exist
        !cached &&
        db.set({
            data: result,
            fileName: url,
            mapName: chosenMap.id,
        });

        setisDataProcessing(true);
        const line = result;
        const lineNumber = line.length;
        let zzoom = null;
        let polygons = [];
        let sPolygons = [];
        let labels = [];
        for (let i = 0; i <= lineNumber; i++) {
            if (i === lineNumber || line[i].length === 1) {
                if (i > 0) {
                    let sameColor = {};
                    polygons.push(...sPolygons);
                    for (let j = 0; j < polygons.length; j++) {
                        let color = polygons[j][0];
                        let points = [];
                        for (let k = 1; k < polygons[j].length; k += 2)
                            points.push([polygons[j][k], polygons[j][k + 1]]);
                        if (color in sameColor)
                            sameColor[color].push(points);
                        else
                            sameColor[color] = [points];
                    }
                    setData((prevData) => [...prevData, [zzoom, sameColor]]);
                    setLabel((prevLabel) => [...prevLabel, [zzoom, labels]]);
                    polygons = [];
                    sPolygons = [];
                    labels = [];
                }
                if (i < lineNumber)
                    zzoom = Number(line[i][0]);
                continue;
            }
            if (line[i][0] === 'P') {
                polygons.push(line[i].slice(1));
            }
            if (line[i][0] === 'S') {
                sPolygons.push(line[i].slice(1));
            }
            if (line[i][0] === 'L') {
                labels.push({
                    text: line[i][1],
                    point: [line[i][2], line[i][3]],
                    size: line[i][4],
                    color: `#${(Number(line[i][5]) % 0x1000000).toString(16)}`,
                    opacity: Number(line[i][5]) / 0x1000000 / 255.0,
                })
            }
        }
        setisDataProcessing(false);
        setData((prevData) => [...prevData]);
        setLabel((prevData) => [...prevData]);
    };

    const parseFile = async (url, key) => {
        setData([]);
        setLabel([]);
        setIsDataFetching(true);
        const _cached = await db.get(url);
        if (_cached.length) {
            getData(url, _cached[0].data, true);
        } else {
            if (key) {
                const response = await axios({
                    url,
                    method: 'GET',
                    responseType: 'blob',
                });
                const decrypted = decryptPrivateMap(response.data, key);
                decrypted &&
                Papa.parse(decrypted, {
                    complete: (result) => getData(url, result.data, false),
                });
            } else {
                Papa.parse(url, {
                    download: true,
                    complete: (result) => getData(url, result.data, false),
                });
            }
        }
    };

    const findZoomLevels = useCallback(() => {
        const result = [];
        data.map((element) => result.push(element[0]));
        return result;
    }, [data]);

    const findZoom = useCallback(() => {
        const inverseZoomLevel = 10 * Math.pow(2, -(map && map.getZoom()));
        const zoomLevels = data && findZoomLevels();
        for (let i = 0; i < zoomLevels.length - 1; i++) {
            if (inverseZoomLevel <= zoomLevels[i]) {
                setZoom(i);
                break;
            } else if (
                inverseZoomLevel > zoomLevels[i] &&
                inverseZoomLevel <= zoomLevels[i + 1]
            ) {
                setZoom(i + 1);
                break;
            } else {
                setZoom(zoomLevels.length - 1)
            }
        }
    }, [map, data, findZoomLevels]);

    useEffect(() => {
        findZoom();
    }, [findZoom, data]);

    useEffect(() => {
        map &&
        map.on('zoom', function () {
            findZoom();
        });
    });

    const hasPrivateAccess = () => {
        return (
            user &&
            user.permissions.filter((perm) => perm === 'webmap').length &&
            user.permissions.some((perm) => {
                return perm.includes('maps_');
            })
        );
    };

    useEffect(() => {
        dispatch(fetchMaps());
        hasPrivateAccess() && dispatch(fetchPrivateMaps(token));
        setMap(
            new window.L.Map('map', {
                key: process.env.REACT_APP_MAP_TOKEN,
                maptype: 'dreamy',
                poi: true,
                traffic: false,
                zoomControl: false,
                center: [32.4279, 53.688],
                zoom: 4.2,
            })
        );
    }, [dispatch]);

    useEffect(() => {
        mapList && setChosenMap(mapList[0]);
    }, [mapList]);

    useEffect(() => {
        chosenMap &&
        parseFile(
            `${process.env.REACT_APP_MAP_CDN}${chosenMap.id}.${chosenMap.version}.csv`,
            chosenMap.key
        );
    }, [chosenMap]);

    useEffect(() => {
        if (isDataProcessing)
            return;
        clearPolygon();
        if (!((data || {})[zoom] || [])[1]) {
            return;
        }
        console.log("drawpolygon")
        for (let key in data[zoom][1]) {
            if (Object.prototype.hasOwnProperty.call(data[zoom][1], key))
                drawPolygon(key, data[zoom][1][key]);
        }
    }, [map, zoom, data, clearPolygon, drawPolygon]);

    useEffect(() => {
        if (isDataProcessing)
            return;
        clearLabel();
        if (!((label || {})[zoom] || [])[1]) {
            return;
        }
        // TODO clean this shit
        let root = document.documentElement;
        root.style.setProperty('--label-color', '#000000');
        root.style.setProperty('--label-size', 10);
        for (let entry of label[zoom][1]) {
            window.L.marker(entry.point, {
                opacity: 0,
            }).bindTooltip(entry.text, {
                permanent: true,
                className: 'map-label',
                direction: 'top',
            }).addTo(map);
        }
    }, [map, label, zoom, clearLabel]);

    const handleLocate = async () => {
        const myLatLngLocation = await utility.getCurrentPosition();
        map.flyTo(myLatLngLocation, 15);
    };

    const clickMenu = (event) => {
        setAnchorEl(event.currentTarget);
    };

    const closeMenu = (value) => {
        value && setChosenMap(value);
        setAnchorEl(null);
    };

    const renderMenu = () => {
        return (
            <Menu
                classes={{
                    paper: 'map-menu',
                }}
                anchorEl={anchorEl}
                keepMounted
                open={Boolean(anchorEl)}
                onClose={() => closeMenu()}
            >
                {mapList &&
                mapList.map((item) => {
                    return (
                        <MenuItem
                            key={item.id}
                            classes={{root: 'map-menu-item'}}
                            onClick={() => closeMenu(item)}
                        >
                            {item.name}
                        </MenuItem>
                    );
                })}
            </Menu>
        );
    };

    return (
        <div className={`contentWrapper MapWrapper`}>
            <div className="alerts">
                <Collapse
                    className="map-alert-wrapper"
                    in={isDataFetching || isMapFetching || isPrivateMapFetching}
                    addEndListener={null}
                >
                    <Alert
                        severity="info"
                        action={
                            <IconButton
                                color="inherit"
                                size="small"
                                onClick={() => {
                                    setIsDataFetching(false);
                                }}
                            >
                                <CloseIcon fontSize="inherit"/>
                            </IconButton>
                        }
                    >
                        تا دریافت اطلاعات منتظر بمانید.
                    </Alert>
                </Collapse>
                {serverError && (
                    <Collapse
                        className="map-alert-wrapper"
                        in={vpnAlert}
                        addEndListener={null}
                    >
                        <Alert
                            severity="warning"
                            action={
                                <IconButton
                                    color="inherit"
                                    size="small"
                                    onClick={() => {
                                        setVpnAlert(false);
                                    }}
                                >
                                    <CloseIcon fontSize="inherit"/>
                                </IconButton>
                            }
                        >
                            در صورت اتصال، vpn دستگاه را قطع کنید.
                        </Alert>
                    </Collapse>
                )}
            </div>
            <div className="map-button-wrapper">
                <button
                    type="button"
                    className="map-button"
                    onClick={() => handleLocate()}
                >
                    <MyLocationIcon/>
                </button>
                <button
                    type="button"
                    name="chosenMap"
                    className="map-button type"
                    onClick={(e) => clickMenu(e)}
                >
                    <div>{(chosenMap || {}).name}</div>
                    <ExpandMoreIcon/>
                </button>
            </div>
            <div
                id="map"
                style={{
                    position: 'fixed',
                    top: 0,
                    right: 0,
                    width: '100vw',
                    height: '100vh',
                    zIndex: 0,
                }}
            />
            <div className="comment-wrapper">
                <div className="map-comment">{(chosenMap || {}).comment || 'ــ'}</div>
            </div>
            <div className="logo-wrapper right">
                <img src={logo} alt=""/>
            </div>
            <div className="logo-wrapper left">
                <img src={neshanLogo} alt=""/>
            </div>
            {renderMenu()}
        </div>
    );
}
Example #27
Source File: BlockiesMenu.js    From lrc-staking-dapp with MIT License 4 votes vote down vote up
BlockiesMenu = React.memo(({
  classes, messages, walletAddress, onEditAddress, onLogout,
}) => {
  const [anchorEl, setAnchorEl] = React.useState(null);

  const BlockiesRound = ({ walletAddressBlockies }) => (
    <div className="d-block p-0 avatar-icon-wrapper rounded-circle m-0 border-3 border-primary">
      <div className="rounded-circle border-3 border-white overflow-hidden">
        <Blockies
          seed={walletAddressBlockies.toLowerCase()}
          size={8}
          scale={10}
          className="identicon"
        />
      </div>
    </div>
  );
  BlockiesRound.propTypes = { walletAddressBlockies: PropTypes.string.isRequired };

  return (
    <div>
      <div
        tabIndex="0"
        role="button"
        className={`avatar-icon-wrapper rounded-circle mx-auto ${classes.btnBlockies}`}
        onClick={(e) => setAnchorEl(e.currentTarget)}
        onKeyDown={(e) => { if (e.key === 'Enter' && !!walletAddress) setAnchorEl(e.currentTarget); }}
      >
        <BlockiesRound walletAddressBlockies={walletAddress} />
        <span className={classes.angleDownBlockies}>
          <FontAwesomeIcon icon={['fas', 'angle-down']} className="opacity-5" />
        </span>
      </div>
      <Menu
        anchorEl={anchorEl}
        keepMounted
        getContentAnchorEl={null}
        open={Boolean(anchorEl)}
        anchorOrigin={{
          horizontal: 'center',
          vertical: 'top',
        }}
        transformOrigin={{
          horizontal: 'center',
          vertical: 'top',
        }}
        onClose={() => setAnchorEl(null)}
        className="ml-2"
      >
        <div className="dropdown-menu-right dropdown-menu-lg overflow-hidden p-0">
          <List className="text-left bg-transparent d-flex align-items-center flex-column pt-0">
            <div className="avatar-icon-wrapper rounded-circle mx-auto">
              <BlockiesRound walletAddressBlockies={walletAddress} />
            </div>
            <ShortAddressCopyButton messages={messages} walletAddress={walletAddress} />
            <Divider className="w-100 mt-2" />
            <ListItem button onClick={() => window.open(`https://etherscan.io/address/${walletAddress}`, '_blank')}>
              <span className="font-size-sm font-weight-bold">
                <span className={classes.iconLeft}><FontAwesomeIcon icon={['fab', 'ethereum']} /></span>
                Etherscan
              </span>
            </ListItem>
            <ListItem button onClick={onEditAddress}>
              <span className="font-size-sm font-weight-bold">
                <span className={classes.iconLeft}><FontAwesomeIcon icon={['fas', 'search']} /></span>
                {messages['Watch address']}
              </span>
            </ListItem>
            <ListItem button onClick={onLogout}>
              <span className="font-size-sm font-weight-bold">
                <span className={classes.iconLeft}><FontAwesomeIcon icon={['fas', 'unlink']} /></span>
                {messages.Logout}
              </span>
            </ListItem>
            <Divider className="w-100" />
            <ListItem button onClick={() => window.open('https://etherscan.io/address/lrctoken.eth', '_blank')}>
              <span className="font-size-sm font-weight-bold">
                <span className={classes.iconLeft}><img src={lrc} alt="Loopring logo" width={14} /></span>
                {messages['LRC token']}
              </span>
            </ListItem>
            <ListItem button onClick={() => window.open('https://etherscan.io/address/stakingpool.lrctoken.eth', '_blank')}>
              <span className="font-size-sm font-weight-bold">
                <span className={classes.iconLeft}><FontAwesomeIcon icon={['fab', 'fort-awesome']} /></span>
                {messages['Staking pool']}
              </span>
            </ListItem>
            <ListItem button onClick={() => window.open('https://etherscan.io/address/feevault.lrctoken.eth', '_blank')}>
              <span className="font-size-sm font-weight-bold">
                <span className={classes.iconLeft}><FontAwesomeIcon icon={['fas', 'donate']} /></span>
                {messages['Fee vault']}
              </span>
            </ListItem>
            <Divider className="w-100" />
            <ListItem button onClick={() => window.open('https://loopring.org', '_blank')}>
              <span className="font-size-sm font-weight-bold">
                <span className={classes.iconLeft}><FontAwesomeIcon icon={['fas', 'globe']} /></span>
                Loopring
              </span>
            </ListItem>
            <ListItem button onClick={() => window.open('https://loopring.io', '_blank')}>
              <span className="font-size-sm font-weight-bold">
                <span className={classes.iconLeft}><FontAwesomeIcon icon={['fas', 'exchange-alt']} /></span>
                {messages.Exchange}
              </span>
            </ListItem>
            <ListItem button onClick={() => window.open('https://duneanalytics.com/loopring', '_blank')}>
              <span className="font-size-sm font-weight-bold">
                <span className={classes.iconLeft}><FontAwesomeIcon icon={['fas', 'chart-pie']} /></span>
                {messages.Analytics}
              </span>
            </ListItem>
            <ListItem button onClick={() => window.open('https://discord.gg/KkYccYp', '_blank')}>
              <span className="font-size-sm font-weight-bold">
                <span className={classes.iconLeft}><FontAwesomeIcon icon={['fab', 'discord']} /></span>
                Discord
              </span>
            </ListItem>
            <ListItem button onClick={() => window.open('https://twitter.com/loopringorg', '_blank')}>
              <span className="font-size-sm font-weight-bold">
                <span className={classes.iconLeft}><FontAwesomeIcon icon={['fab', 'twitter']} /></span>
                Twitter
              </span>
            </ListItem>
          </List>
        </div>
      </Menu>
    </div>
  );
})
Example #28
Source File: Navbar.js    From Kurakoo with MIT License 4 votes vote down vote up
export default function Navbar() {
    const classes = useStyles();
    const [openPopup, setOpenPopup] = useState(false);

    const handleOpen = () => {
        setOpenPopup(true);
      };

      const handleCloseModal = () => {
        setOpenPopup(false);
      }

    const [anchorEl, setAnchorEl] = useState(null);

    const handleClick = (event) => {
        setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
        setAnchorEl(null);
    };
    return (
        <div>
            <nav className="Nav">
                <div>
                    <Link to="/">
                        <img id="logo" src={Logo} alt="alt" />
                    </Link>
                </div>
                <div className="nav-options">
                    <div className="option">{data.svg1}</div>

                    <div className="option search">
                        <SearchBar />
                    </div>
                    <div className="option">
                        <Button
                            variant="contained"
                            color="secondary"
                            size="large"
                            onClick={handleOpen}
                        >
                            <QuestionAnswerIcon /> &emsp; Ask Question
                        </Button>
                    </div>
                    <div className="option">
                        <Link to="/notification"> {data.notification}</Link>
                    </div>

                    <div className="option">
                        <Button
                            onClick={handleClick}
                            variant="contained"
                            color="secondary"
                            startIcon={<AccountCircleRoundedIcon />}
                        >
                            <b>User</b>
                        </Button>
                        <Menu
                            id="simple-menu"
                            anchorEl={anchorEl}
                            keepMounted
                            open={Boolean(anchorEl)}
                            onClose={handleClose}
                        >
                            <MenuItem onClick={handleClose}>
                                <EditIcon />
                                &emsp;Profile
                            </MenuItem>
                            <MenuItem onClick={handleClose}>
                                <ExitToAppOutlinedIcon />
                                &emsp;Logout
                            </MenuItem>
                        </Menu>
                    </div>
                </div>
            </nav>
            <Modal
            open ={openPopup}
            onClose={handleCloseModal}>
                <div  className={classes.paper}>
                <AddAQuestion/>
                </div>

            </Modal>
        </div>
    );
}
Example #29
Source File: Profile.jsx    From zubhub with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @function Profile View
 * @author Raymond Ndibe <[email protected]>
 *
 * @todo - describe function's signature
 */
function Profile(props) {
  const username_el = React.useRef(null);
  const classes = useStyles();
  const common_classes = useCommonStyles();
  const username = props.match.params.username || props.auth.username;

  const [state, setState] = React.useState({
    results: [],
    loading: true,
    profile: {},
    open_delete_account_modal: false,
    dialog_error: null,
    more_anchor_el: null,
    drafts: [],
  });

  React.useEffect(() => {
    const promises = [getUserProfile(props)];
    if (username === props.auth.username) {
      promises.push(
        ProjectActions.getUserDrafts({
          username,
          token: props.auth.token,
          t: props.t,
          limit: 4,
        }),
      );
    }

    Promise.all(promises).then(values => {
      const obj = values[0];
      const drafts = values[1] || {};

      if (obj.profile) {
        parseComments(obj.profile.comments);
      }
      handleSetState({ ...obj, ...drafts });
    });
  }, []);

  const handleSetState = obj => {
    if (obj) {
      Promise.resolve(obj).then(obj => {
        setState(state => ({ ...state, ...obj }));
      });
    }
  };

  const {
    results: projects,
    profile,
    loading,
    open_delete_account_modal,
    dialog_error,
    more_anchor_el,
    drafts,
  } = state;

  const more_menu_open = Boolean(more_anchor_el);
  const { t } = props;

  if (loading) {
    return <LoadingPage />;
  } else if (profile && Object.keys(profile).length > 0) {
    return (
      <>
        <Box className={classes.root}>
          <Paper className={classes.profileHeaderStyle}>
            <Container maxWidth="md">
              {props.auth.username === profile.username ? (
                <>
                  <CustomButton
                    className={classes.floatRight}
                    onClick={e => handleSetState(handleMoreMenuOpen(e))}
                  >
                    <MoreVertIcon />
                  </CustomButton>
                  <CustomButton
                    className={classes.floatRight}
                    variant="contained"
                    margin="normal"
                    primaryButtonStyle
                    onClick={() => props.history.push('/edit-profile')}
                  >
                    {t('profile.edit')}
                  </CustomButton>
                  <Menu
                    className={classes.moreMenuStyle}
                    disableScrollLock={true}
                    id="profile_menu"
                    anchorEl={more_anchor_el}
                    anchorOrigin={{
                      vertical: 'top',
                      horizontal: 'right',
                    }}
                    keepMounted
                    transformOrigin={{
                      vertical: 'top',
                      horizontal: 'right',
                    }}
                    open={more_menu_open}
                    onClose={e => handleSetState(handleMoreMenuClose(e))}
                  >
                    <MenuItem>
                      <Typography
                        variant="subtitle2"
                        className={common_classes.colorRed}
                        component="span"
                        onClick={() =>
                          handleSetState(handleToggleDeleteAccountModal(state))
                        }
                      >
                        {t('profile.delete.label')}
                      </Typography>
                    </MenuItem>
                  </Menu>
                </>
              ) : (
                <CustomButton
                  className={classes.floatRight}
                  variant="outlined"
                  margin="normal"
                  secondaryButtonStyle
                  onClick={() =>
                    handleSetState(toggleFollow(profile.id, props))
                  }
                >
                  {profile.followers.includes(props.auth.id)
                    ? t('profile.unfollow')
                    : t('profile.follow')}
                </CustomButton>
              )}
              <Box className={classes.avatarBoxStyle}>
                <Avatar
                  className={classes.avatarStyle}
                  src={profile.avatar}
                  alt={profile.username}
                />
              </Box>
              <Box className={classes.ProfileDetailStyle}>
                <Typography
                  className={classes.userNameStyle}
                  component="h1"
                  color="textPrimary"
                >
                  {profile.username}
                </Typography>
                <Box className={classes.tagsContainerStyle}>
                  {sortTags(profile.tags).map(tag => (
                    <Typography
                      key={tag}
                      className={clsx(common_classes.baseTagStyle, {
                        [common_classes.extendedTagStyle]: !isBaseTag(tag),
                      })}
                      component="h2"
                    >
                      {tag}
                    </Typography>
                  ))}
                </Box>
                {props.auth.username === profile.username ? (
                  <>
                    <Typography className={classes.emailStyle} component="h5">
                      {profile.email}
                    </Typography>
                    <Typography className={classes.emailStyle} component="h5">
                      {profile.phone}
                    </Typography>
                  </>
                ) : null}
                <Divider className={classes.dividerStyle} />
                <Box className={classes.moreInfoBoxStyle}>
                  <Link
                    className={classes.textDecorationNone}
                    to={`/creators/${profile.username}/projects`}
                  >
                    <Typography
                      className={classes.moreInfoStyle}
                      component="h5"
                    >
                      {profile.projects_count} {t('profile.projectsCount')}
                    </Typography>
                  </Link>
                  <Link
                    to={`/creators/${profile.username}/followers`}
                    className={classes.textDecorationNone}
                  >
                    <Typography
                      className={classes.moreInfoStyle}
                      component="h5"
                    >
                      {profile.followers.length} {t('profile.followersCount')}
                    </Typography>
                  </Link>
                  <Link
                    to={`/creators/${profile.username}/following`}
                    className={classes.textDecorationNone}
                  >
                    <Typography
                      className={classes.moreInfoStyle}
                      component="h5"
                    >
                      {profile.following_count} {t('profile.followingCount')}
                    </Typography>
                  </Link>
                  {profile.members_count !== null ? (
                    <Link
                      to={`/creators/${profile.username}/members`}
                      className={classes.textDecorationNone}
                    >
                      <Typography
                        className={classes.moreInfoStyle}
                        component="h5"
                      >
                        {profile.members_count} {t('profile.membersCount')}
                      </Typography>
                    </Link>
                  ) : null}
                </Box>
              </Box>
            </Container>
          </Paper>

          <Container maxWidth="md">
            <Paper className={classes.profileLowerStyle}>
              <Typography
                gutterBottom
                component="h2"
                variant="h6"
                color="textPrimary"
                className={classes.titleStyle}
              >
                {!profile.members_count
                  ? t('profile.about.label1')
                  : t('profile.about.label2')}
              </Typography>
              {profile.bio
                ? profile.bio
                : !profile.members_count
                ? t('profile.about.placeholder1')
                : t('profile.about.placeholder2')}
            </Paper>

            {profile.projects_count > 0 || drafts.length > 0 ? (
              username === props.auth.username ? (
                <ProjectsDraftsGrid
                  profile={profile}
                  projects={projects}
                  drafts={drafts}
                  handleSetState={handleSetState}
                  {...props}
                />
              ) : (
                <Paper className={classes.profileLowerStyle}>
                  <Typography
                    gutterBottom
                    component="h2"
                    variant="h6"
                    color="textPrimary"
                    className={classes.titleStyle}
                  >
                    {t('profile.projects.label')}
                    <CustomButton
                      className={clsx(classes.floatRight)}
                      variant="outlined"
                      margin="normal"
                      secondaryButtonStyle
                      onClick={() =>
                        props.history.push(
                          `/creators/${profile.username}/projects`,
                        )
                      }
                    >
                      {t('profile.projects.viewAll')}
                    </CustomButton>
                  </Typography>
                  <Grid container>
                    {Array.isArray(projects) &&
                      projects.map(project => (
                        <Grid
                          item
                          xs={12}
                          sm={6}
                          md={6}
                          className={classes.projectGridStyle}
                          align="center"
                        >
                          <Project
                            project={project}
                            key={project.id}
                            updateProjects={res =>
                              handleSetState(
                                updateProjects(res, state, props, toast),
                              )
                            }
                            {...props}
                          />
                        </Grid>
                      ))}
                  </Grid>
                </Paper>
              )
            ) : null}
            <Comments
              context={{ name: 'profile', body: profile }}
              handleSetState={handleSetState}
              {...props}
            />
          </Container>
        </Box>
        <Dialog
          open={open_delete_account_modal}
          onClose={() => handleSetState(handleToggleDeleteAccountModal(state))}
          aria-labelledby={t('profile.delete.ariaLabels.deleteAccount')}
        >
          <DialogTitle id="delete-project">
            {t('profile.delete.dialog.primary')}
          </DialogTitle>
          <Box
            component="p"
            className={dialog_error !== null && classes.errorBox}
          >
            {dialog_error !== null && (
              <Box component="span" className={classes.error}>
                {dialog_error}
              </Box>
            )}
          </Box>{' '}
          <DialogContent>
            <Typography>{t('profile.delete.dialog.secondary')}</Typography>
            <FormControl
              className={clsx(classes.margin, classes.textField)}
              variant="outlined"
              size="medium"
              fullWidth
              margin="normal"
            >
              <InputLabel
                className={classes.customLabelStyle}
                htmlFor="username"
              >
                {t('profile.delete.dialog.inputs.username')}
              </InputLabel>
              <OutlinedInput
                className={classes.customInputStyle}
                ref={username_el}
                name="username"
                type="text"
                labelWidth={120}
              />
            </FormControl>
          </DialogContent>
          <DialogActions>
            <CustomButton
              variant="outlined"
              onClick={() =>
                handleSetState(handleToggleDeleteAccountModal(state))
              }
              color="primary"
              secondaryButtonStyle
            >
              {t('profile.delete.dialog.cancel')}
            </CustomButton>
            <CustomButton
              variant="contained"
              onClick={e =>
                handleSetState(deleteAccount(username_el, props, state))
              }
              dangerButtonStyle
              customButtonStyle
            >
              {t('profile.delete.dialog.procceed')}
            </CustomButton>
          </DialogActions>
        </Dialog>
      </>
    );
  } else {
    return <ErrorPage error={t('profile.errors.profileFetchError')} />;
  }
}