@material-ui/core#IconButton TypeScript Examples

The following examples show how to use @material-ui/core#IconButton. 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: index.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 6 votes vote down vote up
function GitHubGistWidget(props: WidgetArgs) {
  const classes = useStyles(props);
  const { t } = useTranslation();
  const [url, setURL] = useState<string>("");

  const setGistURL = useCallback(
    (url: string) => {
      try {
        const location = new URL(url);
        if (location.host !== "gist.github.com") {
          return;
        } else {
          props.setAttributes({
            url: location.origin + location.pathname,
          });
        }
      } catch (error) {}
    },
    [props]
  );

  if (props.attributes["url"]) {
    return (
      <Box className={"preview github-gist"} style={{ whiteSpace: "normal" }}>
        <Gist url={props.attributes["url"]}></Gist>
        {!props.isPreview && (
          <Box className={clsx(classes.actionButtonsGroup)}>
            <IconButton onClick={() => props.removeSelf()}>
              <TrashCanOutline></TrashCanOutline>
            </IconButton>
          </Box>
        )}
      </Box>
    );
  }

  if (props.isPreview) {
    return null;
  }

  return (
    <Card elevation={2} className={clsx(classes.card)}>
      <Typography variant={"h5"}>
        {t("widget/crossnote.github_gist/title")}
      </Typography>
      <TextField
        label={t("widget/crossnote/github_gist/enter-github-gist-url")}
        placeholder={"https://gist.github.com/..."}
        value={url}
        onChange={(event) => setURL(event.target.value)}
        fullWidth={true}
        onKeyUp={(event) => {
          if (event.which === 13) {
            setGistURL(url);
          }
        }}
      ></TextField>
      <Box className={clsx(classes.actionButtonsGroup)}>
        <Tooltip title={t("general/Delete")}>
          <IconButton onClick={() => props.removeSelf()}>
            <TrashCan></TrashCan>
          </IconButton>
        </Tooltip>
      </Box>
    </Card>
  );
}
Example #2
Source File: Snackbar.tsx    From Demae with MIT License 6 votes vote down vote up
Bar = ({ open, severity, vertical, message, onClose }: { open: boolean, severity: Severity, vertical?: "top" | "bottom", message?: string, onClose: (event: React.SyntheticEvent | React.MouseEvent, reason?: string) => void }) => {
	if (open) {
		return (
			<Snackbar
				anchorOrigin={{
					vertical: vertical || "top",
					horizontal: "center",
				}}
				open={open}
				autoHideDuration={2800}
				onClose={onClose}
				message={
					<Box display="flex" alignItems="center" fontSize={14} fontWeight={400}>
						{severity === "error" && <ErrorIcon fontSize="small" style={{ marginRight: "8px", color: ErrorColor }} />}
						{severity === "warning" && <WarningIcon fontSize="small" style={{ marginRight: "8px", color: WarningColor }} />}
						{severity === "info" && <InfoIcon fontSize="small" style={{ marginRight: "8px", color: InfoColor }} />}
						{severity === "success" && <CheckCircleIcon fontSize="small" style={{ marginRight: "8px", color: SuccessColor }} />}
						{message}
					</Box>
				}
				action={
					<React.Fragment>
						<IconButton size="small" aria-label="close" color="inherit" onClick={onClose}>
							<CloseIcon fontSize="small" />
						</IconButton>
					</React.Fragment>
				}
			/>
		)
	}
	return <></>
}
Example #3
Source File: Snackbar.stories.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
ActionSnackbar = styled(
  ({
    close,
    ...props
  }: SnackbarContentProps & {
    close?: () => void;
  }) => {
    return (
      <MuiSnackbarContent
        {...props}
        action={[
          <IconButton
            key="close"
            aria-label="close"
            color="inherit"
            onClick={close}
          >
            <Close />
          </IconButton>,
        ]}
      />
    );
  },
)``
Example #4
Source File: Label.tsx    From firetable with Apache License 2.0 6 votes vote down vote up
export default function Label({
  label,
  children,
  hint,
  ...props
}: ILabelProps) {
  const classes = useStyles();

  return (
    <FormLabel className={classes.root} {...props}>
      {label || children}

      {hint && (
        <Tooltip title={hint}>
          <IconButton aria-label="delete">
            <HelpIcon />
          </IconButton>
        </Tooltip>
      )}
    </FormLabel>
  );
}
Example #5
Source File: gameCard.tsx    From mano-aloe with MIT License 6 votes vote down vote up
renderGame(): JSX.Element {
        const gameUrl = linkToString(this.props.object.gameLink);
        return (
            <div>
                <div className="button-row">
                    <div className="game-text">{this.props.object.title}</div>
                    <div className="button-right">
                        <IconButton onClick={this.toggleGame}>
                            <PlayCircleOutline style={{fontSize: 50, color: 'white'}}/>
                        </IconButton>
                        <IconButton onClick={() => this.launchGameNewWindow(gameUrl)}>
                            <Launch style={{fontSize: 50, color: 'white'}}/>
                        </IconButton>
                    </div>
                </div>
                {this.renderGameThumbnail()}
                <div className="game-description">{this.props.object.description}</div>
                {this.state.renderGame ?
                    this.renderGameWindow() :
                    <div/>}
            </div>
        )
    }
Example #6
Source File: ChevronToggleButton.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
ChevronToggleButton = ({
  isOpen,
  className,
  onClick,
}: {
  isOpen: boolean
  className?: string
  onClick: () => void
}): JSX.Element => {
  const classes = useStyles()
  const toggleClass = isOpen ? classes.rotated : classes.notRotated

  return (
    <IconButton className={clsx(classes.root, toggleClass, className)} aria-label={'Toggle Button'} onClick={onClick}>
      <ChevronRightRoundedIcon />
    </IconButton>
  )
}
Example #7
Source File: ButtonPressIcon.tsx    From Pi-Tool with GNU General Public License v3.0 6 votes vote down vote up
ButtonPressIcon: React.FC<ButtonPressIconProps> = ({ press, isButton }) => {
    const icon = (() => {
        switch (press) {
            case ButtonPress.Long:
                return <RadioButtonCheckedIcon />;
            case ButtonPress.Short:
                return <RadioButtonUncheckedIcon />;
            default:
                return null;
        }
    })();

    if (isButton) {
        return (
            <Box style={{ width: 50, height: 50 }}>
                <IconButton disableRipple={true}>
                    {icon}
                </IconButton>
            </Box>
        );
    } else {
        return (
            <Box>
                {icon}
            </Box>
        );
    }
}
Example #8
Source File: Appbar.tsx    From DamnVulnerableCryptoApp with MIT License 6 votes vote down vote up
Appbar = () => {
  const classes = useStyles();
  const history = useHistory();

  const onLogoClicked = () => {
    history.push("/");
  };

  const onBackClicked = () => {
    history.goBack();
  };

  const isHomePage = () => {
    return history.location.pathname === "/";
  };

  return (
    <AppBar position="sticky" className={classes.appbar}>
      <Toolbar className={classes.toolbar}>
        <Box className={classes.menuLeft}>
          <IconButton edge="start" disabled={isHomePage()} onClick={onBackClicked} className={classes.menuButton} color="inherit" aria-label="menu">
            <ArrowBackIcon />
          </IconButton>
          <img className={classes.menuLogo} src={LogoMenu} onClick={onLogoClicked} alt="DamnVulnerableCryptoApp Logo" />
        </Box>
        <Box display="flex">
          <Link to={"/docs/crypto"} className={classes.docsLink}>Docs</Link>
          <Progress />
        </Box>
      </Toolbar>
      <Loading />
    </AppBar>
  );
}
Example #9
Source File: control_button.tsx    From jupyter-extensions with Apache License 2.0 6 votes vote down vote up
render() {
    return (
      <IconButton
        title={this.state.title}
        color="inherit"
        onClick={() => this._onClick()}
        disabled={this.state.disabled}
      >
        {this.state.icon}
      </IconButton>
    );
  }
Example #10
Source File: ReloadButton.tsx    From SpaceEye with MIT License 6 votes vote down vote up
ReloadButtonComp = withStyles({
    root: {
        position: 'absolute',
        top: '4px',
        right: '4px',
        'z-index': '1',
        transform: 'scale(0.70)',
        padding: '0'
    }
})(IconButton)
Example #11
Source File: index.tsx    From GroupChat with MIT License 6 votes vote down vote up
TopBar: React.FC<Props> = props => {
  return (
    <div className={styles.container}>
      <div className={styles.wrapper}>
        <IconButton className={styles.iconButton} onClick={props.menuClick}>
          <MenuIcon className={styles.menu} fontSize="large" />
        </IconButton>
        <h2 className={styles.title}>{props.title}</h2>
      </div>
    </div>
  );
}
Example #12
Source File: index.tsx    From Lux-Viewer-2021 with Apache License 2.0 6 votes vote down vote up
ZoomInOut = ({
  className,
  handleZoomIn,
  handleZoomOut,
}: ZoomInOutProps) => {
  return (
    <div className={`${className} ZoomInOut`}>
      <IconButton className="zoomin" onClick={handleZoomIn}>
        <img src={ZoomIn} />
      </IconButton>
      <IconButton className="zoomout" onClick={handleZoomOut}>
        <img src={ZoomOut} />
      </IconButton>
    </div>
  );
}
Example #13
Source File: NewsAppBar.tsx    From The-TypeScript-Workshop with MIT License 6 votes vote down vote up
NewsAppBar = () => {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton
            edge="start"
            className={classes.menuButton}
            color="inherit"
            area-label="menu"
          >
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" className={classes.title}>
            News
          </Typography>
          <NewsMenu />
        </Toolbar>
      </AppBar>
    </div>
  );
}
Example #14
Source File: SettingsSwitchAccount.tsx    From twitch-live-extension with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
SettingsSwitchAccount = ({ user }: SettingsSwitchAccountProps) => {
    const classes = useStyles();
    const dispatch: AppDispatch = useDispatch();

    const { loading } = useSelector((state: RootState) => state.common);

    return (
        <ListItem className={classes.root} dense>
            <ListItemIcon className={classes.icon}>
                <PersonIcon />
            </ListItemIcon>
            <ListItemText
                primary={
                    <span>
                        Logged in as <span className={classes.user}>{user?.login}</span>
                    </span>
                }
            />
            <ListItemSecondaryAction>
                <IconButton
                    edge="end"
                    aria-label="delete"
                    size={'small'}
                    className={classes.button}
                    disabled={loading}
                    onClick={async () => await dispatch(switchAccount())}
                >
                    <ExitToAppIcon />
                </IconButton>
            </ListItemSecondaryAction>
        </ListItem>
    );
}
Example #15
Source File: FilterInput.tsx    From ow-mod-manager with MIT License 6 votes vote down vote up
FilterInput: React.FunctionComponent<Props> = ({
  value,
  onChange,
  label,
}) => {
  const [filterText, setFilterText] = useState(value);
  const debouncedFilterText = useDebounce(filterText, 200);

  useEffect(() => {
    onChange(debouncedFilterText);
  }, [debouncedFilterText, onChange]);

  return (
    <OutlinedInput
      margin="dense"
      onChange={({ currentTarget }) => {
        setFilterText(currentTarget.value);
      }}
      value={filterText}
      placeholder={label}
      color="secondary"
      startAdornment={
        <InputAdornment position="start">
          <SearchIcon />
        </InputAdornment>
      }
      endAdornment={
        filterText !== '' && (
          <InputAdornment position="end">
            <IconButton onClick={() => setFilterText('')} size="small">
              <CloseIcon fontSize="small" />
            </IconButton>
          </InputAdornment>
        )
      }
    />
  );
}
Example #16
Source File: field.tsx    From Figurify with Apache License 2.0 6 votes vote down vote up
render() {
        return (
            <div style={{marginBottom: "10px"}}>
                {this.state.x}
                {this.state.y}
                <IconButton style={{...noBorder, marginLeft: "10px"}} onClick={
                    this.props.onDelete
                } aria-label="delete">
                    <DeleteIcon/>
                </IconButton>
            </div>
        );
    }
Example #17
Source File: ControlsSyncProfileGoogle.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
_ControlsSyncProfileGoogle: FunctionComponent<ControlsSyncProfileGoogleProps> = ({
  googleAuthProfile,
}) => {
  const classes = useStyles();

  // Don't display if not logged in.
  if (googleAuthProfile == null) return null;

  return (
    <Box display="flex" flexDirection="column">
      <Box display="flex" flexDirection="row">
        <Avatar alt={googleAuthProfile.name} src={googleAuthProfile.imageUrl} />
        <Box display="flex" className={classes.profileWelcome} flexDirection="column">
          <Typography variant="h5">
            {f('map-ui:welcome-format', { user: googleAuthProfile.givenName })}
          </Typography>
          <Typography variant="subtitle2">{googleAuthProfile.email}</Typography>
        </Box>
      </Box>

      <Box display="flex" flexDirection="row">
        <Typography className={classes.centerVertical} variant="body2">
          {t('map-ui:google-login-success')}
        </Typography>
        <Tooltip title={t('core:sign-out')}>
          <IconButton className={classes.logoutButton} onClick={attemptGoogleSignOut}>
            <LogoutIcon />
          </IconButton>
        </Tooltip>
      </Box>
    </Box>
  );
}
Example #18
Source File: index.tsx    From react-app-architecture with Apache License 2.0 6 votes vote down vote up
export default function BlogPreview({ blog, open, onClose }: Props): ReactElement {
  const classes = useStyles();
  return (
    <Dialog
      fullScreen
      open={open}
      TransitionComponent={Transition}
      PaperProps={{ className: classes.paper }}
      PaperComponent={PaperComponent}
    >
      <AppBar position="fixed" color="secondary">
        <Toolbar>
          <IconButton edge="start" color="inherit" onClick={onClose} aria-label="close">
            <CloseIcon />
          </IconButton>
          <Typography variant="h6" className={classes.title}>
            {blog.title}
          </Typography>
          <Button color="inherit" onClick={onClose}>
            Done
          </Button>
        </Toolbar>
      </AppBar>
      <Grid container justify="center">
        <Grid item xs={12} sm={12} md={8} className={classes.blogContent}>
          {blog?.draftText && <Markdown text={blog.draftText} />}
        </Grid>
      </Grid>
    </Dialog>
  );
}
Example #19
Source File: index.tsx    From aqualink-app with MIT License 6 votes vote down vote up
CustomLink = ({
  to,
  tooltipTitle,
  isIcon,
  content,
  classes,
}: CustomLinkProps) => {
  return (
    <Tooltip title={tooltipTitle} placement="top" arrow>
      <Link className={classes.link} to={to}>
        {isIcon ? (
          <IconButton className={classes.button}>
            <Launch color="primary" />
          </IconButton>
        ) : (
          content
        )}
      </Link>
    </Tooltip>
  );
}
Example #20
Source File: Layout.tsx    From fishbowl with MIT License 6 votes vote down vote up
function Layout(props: { children: React.ReactNode }) {
  const [open, setOpen] = React.useState(false)
  const [message, setMessage] = React.useState<string | null>(null)

  const handleClose = () => setOpen(false)

  return (
    <Box>
      <Snackbar
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
        open={open}
        onClose={handleClose}
        autoHideDuration={3000}
        message={message}
        TransitionComponent={GrowTransition}
        action={
          <IconButton
            size="small"
            aria-label="close"
            color="inherit"
            onClick={handleClose}
          >
            <CloseIcon fontSize="small" />
          </IconButton>
        }
      ></Snackbar>
      <NotificationContext.Provider
        value={{
          send: (message: string) => {
            setMessage(message)
            setOpen(true)
          },
        }}
      >
        {props.children}
      </NotificationContext.Provider>
    </Box>
  )
}
Example #21
Source File: TechDocsPage.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
TechDocsThemeToggle = () => {
  const appThemeApi = useApi(appThemeApiRef);
  const classes = useStyles();
  const [theme, setTheme] = useState<Themes>(
    (appThemeApi.getActiveThemeId() as Themes) || Themes.LIGHT,
  );

  const themes = {
    [Themes.LIGHT]: {
      icon: DarkIcon,
      title: 'Dark theme',
    },
    [Themes.DARK]: {
      icon: LightIcon,
      title: 'Light theme',
    },
  };

  const { title, icon: Icon } = themes[theme];

  const handleSetTheme = () => {
    setTheme(prevTheme => {
      const newTheme = prevTheme === Themes.LIGHT ? Themes.DARK : Themes.LIGHT;
      appThemeApi.setActiveThemeId(newTheme);
      return newTheme;
    });
  };

  return (
    <Box display="flex" alignItems="center" mr={2}>
      <Tooltip title={title} arrow>
        <IconButton size="small" onClick={handleSetTheme}>
          <Icon className={classes.headerIcon} />
        </IconButton>
      </Tooltip>
    </Box>
  );
}
Example #22
Source File: index.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 5 votes vote down vote up
function KanbanColumnHeaderDisplay(props: KanbanColumnHeaderProps) {
  const classes = useStyles(props);
  const { t } = useTranslation();
  const column = props.column;
  const board = props.board;
  const isPreview = props.isPreview;
  const refreshBoard = props.refreshBoard;
  const [clickedTitle, setClickedTitle] = useState<boolean>(false);
  const [titleValue, setTitleValue] = useState<string>(column.title);

  useEffect(() => {
    if (!clickedTitle && titleValue !== column.title) {
      column.title = titleValue || t("general/Untitled");
      setTitleValue(column.title);
      refreshBoard(board);
    }
  }, [clickedTitle, board, column.title, titleValue, t, refreshBoard]);

  return (
    <Box className={clsx(classes.columnHeader)}>
      <Box>
        {clickedTitle ? (
          <TextField
            value={titleValue}
            onChange={(event) => {
              setTitleValue(event.target.value);
            }}
            onBlur={() => {
              setClickedTitle(false);
            }}
            onKeyUp={(event) => {
              if (event.which === 13) {
                setClickedTitle(false);
              }
            }}
          ></TextField>
        ) : (
          <Typography
            variant={"body1"}
            style={{ cursor: "text" }}
            onClick={() => {
              if (!isPreview) {
                setClickedTitle(true);
              }
            }}
          >
            {titleValue}
          </Typography>
        )}
      </Box>
      {!isPreview && (
        <Box>
          <IconButton
            onClick={() => {
              const card: KanbanCard = {
                id: Date.now(),
                title: "", //"Card " + column.cards.length,
                description: t("general/empty"),
              };
              if (column) {
                column.cards.push(card);
              }
              props.refreshBoard(board);
            }}
          >
            <CardPlus></CardPlus>
          </IconButton>
          <IconButton
            onClick={() => {
              board.columns = board.columns.filter((l) => column.id !== l.id);
              props.refreshBoard(board);
            }}
          >
            <Close></Close>
          </IconButton>
        </Box>
      )}
    </Box>
  );
}
Example #23
Source File: Layout.tsx    From Demae with MIT License 5 votes vote down vote up
AccountMenu = () => {

	const [user] = useUser()
	const [roles] = useRoles()

	const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
	const menuOpen = Boolean(anchorEl)
	const handleMenu = (event: React.MouseEvent<HTMLElement>) => {
		setAnchorEl(event.currentTarget);
	}
	const handleClose = () => {
		setAnchorEl(null);
	}

	if (user) {
		return (
			<>
				<IconButton
					onClick={handleMenu}
					color="inherit"
				>
					<AccountCircle />
				</IconButton>
				<Menu
					style={{ width: "120px" }}
					anchorEl={anchorEl}
					anchorOrigin={{ vertical: "top", horizontal: "right", }}
					keepMounted
					transformOrigin={{ vertical: "top", horizontal: "right", }}
					open={menuOpen}
					onClose={handleClose}
				>
					{roles.map(role => <UserMenuItem key={role.id} role={role} />)}
					<Divider />
					<MenuItem key={"signout"} onClick={async () => {
						await firebase.auth().signOut()
					}}>SignOut</MenuItem>
				</Menu>
			</>
		)
	} else {
		return (
			<IconButton
				color="inherit"
			>
				<AccountCircle />
			</IconButton>
		)
	}
}
Example #24
Source File: BetaBanner.tsx    From akashlytics with GNU General Public License v3.0 5 votes vote down vote up
BetaBanner = () => {
  const [isBetaBarVisible, setIsBetaBarVisible] = useState(false);
  const classes = useStyles();

  useEffect(() => {
    const isBetaBarSeen = localStorage.getItem("isBetaBarSeen");
    setIsBetaBarVisible(isBetaBarSeen === null ? true : false);
  }, []);

  const hideIsBetaBarVisible = () => {
    localStorage.setItem("isBetaBarSeen", "true");
    setIsBetaBarVisible(false);
  };

  return (
    <>
      {isBetaBarVisible && (
        <AppBar position="static" color="default" className={classes.root}>
          <Toolbar>
            <Chip label="BETA" color="primary" className={classes.betaChip} />
            <div className={classes.betaText}>
              <Box marginBottom=".5rem">
                <Typography variant="body2">
                  Akashlytics Deploy is now currently in open BETA.
                </Typography>
              </Box>
              <Button
                component={Link}
                to="/deploy"
                variant="contained"
                size="small"
                onClick={() => hideIsBetaBarVisible()}
              >
                Take a look!
              </Button>
            </div>

            <div className={classes.grow} />
            <IconButton
              aria-label="Close beta app bar"
              color="inherit"
              onClick={() => hideIsBetaBarVisible()}
            >
              <CloseIcon />
            </IconButton>
          </Toolbar>
        </AppBar>
      )}
    </>
  );
}
Example #25
Source File: index.tsx    From firetable with Apache License 2.0 5 votes vote down vote up
export default function HomeNavigation({
  children,
  open,
  setOpen,
  handleCreateTable,
}: IHomeNavigationProps) {
  const classes = useStyles();
  const trigger = useScrollTrigger({ disableHysteresis: true, threshold: 0 });

  return (
    <Grid
      container
      wrap="nowrap"
      alignItems="flex-start"
      className={clsx(open && classes.open)}
    >
      <Grid item className={classes.navDrawerContainer}>
        <NavDrawer
          open={open}
          onClose={() => setOpen(false)}
          handleCreateTable={handleCreateTable}
        />
      </Grid>

      <Grid item xs>
        <AppBar
          color="inherit"
          elevation={trigger ? 4 : 0}
          className={classes.appBar}
        >
          <Container>
            <Toolbar className={clsx(classes.maxHeight, classes.toolbar)}>
              <IconButton
                aria-label="Open navigation drawer"
                onClick={() => setOpen(true)}
                edge="start"
                className={classes.openButton}
              >
                <MenuIcon />
              </IconButton>

              <div className={classes.logo}>
                <FiretableLogo />
              </div>

              <UserMenu />
            </Toolbar>
          </Container>
        </AppBar>

        {children}
      </Grid>
    </Grid>
  );
}
Example #26
Source File: SnackbarNotification.tsx    From firebase-react-typescript-project-template with MIT License 5 votes vote down vote up
SnackbarNotification = () => {
  const classes = useStyles({});
  const {
    isOpen,
    message,
    variant,
    closeNotification,
  } = useSnackbarNotification();

  return (
    <Snackbar
      anchorOrigin={{
        vertical: "bottom",
        horizontal: "center",
      }}
      TransitionComponent={SlideTransition}
      open={isOpen}
      autoHideDuration={5000}
      onClose={closeNotification}
      className={classes.root}
    >
      <SnackbarContent
        classes={{
          root: clsx(classes.snackbarContent, classes[variant]),
          message: classes.message,
        }}
        message={
          <>
            <Typography variant="body1" className={classes.messageText}>
              {message}
            </Typography>
            <IconButton
              key="close"
              color="inherit"
              onClick={closeNotification}
              className={classes.closeButton}
            >
              <X />
            </IconButton>
          </>
        }
      />
    </Snackbar>
  );
}
Example #27
Source File: MainAppBar.tsx    From clarity with Apache License 2.0 5 votes vote down vote up
MainAppBar = observer((props: Props) => {
  const classes = useStyles();
  const connected = props.connectionContainer.connectionStatus;

  if (props.authContainer.hasCreatedVault && props.authContainer.isUnLocked) {
    return (
      <React.Fragment>
        <AppBar
          position="static"
          className={classes.root}
          color={'transparent'}
        >
          <Toolbar>
            <IconButton edge="start" component={Link} to={'/'}>
              <HomeIcon />
            </IconButton>
            <Button
              // Toggles connection status
              variant="outlined"
              className={classes.title}
              color={connected ? 'primary' : 'default'}
              size="small"
              onClick={() => {
                if (connected) {
                  props.connectionContainer.disconnectFromSite();
                } else {
                  props.connectionContainer.connectToSite();
                }
              }}
            >
              {connected ? 'Connected' : 'Disconnected'}
            </Button>
            <MoreMenu authContainer={props.authContainer} />
          </Toolbar>
        </AppBar>
        <div className={classes.toolbarMargin}></div>
      </React.Fragment>
    );
  } else {
    return <div className={classes.toolbarMargin}></div>;
  }
})
Example #28
Source File: MetaMaskConnector.tsx    From metamask-snap-polkadot with Apache License 2.0 5 votes vote down vote up
MetaMaskConnector = () => {

    const [state, dispatch] = useContext(MetaMaskContext);

    useEffect( () => {
        (async () => {
            if(await isPolkadotSnapInstalled()) {
                dispatch({type: MetamaskActions.SET_INSTALLED_STATUS, payload: {isInstalled: true}});
            }
        })();
    }, [dispatch]);

    const installSnap = useCallback(async () => {
       const isInitiated = await installPolkadotSnap();
       if(!isInitiated) {
           dispatch({type: MetamaskActions.SET_INSTALLED_STATUS, payload: {isInstalled: false, message: "Please accept snap installation prompt"}})
       } else {
           dispatch({type: MetamaskActions.SET_INSTALLED_STATUS, payload: {isInstalled: true}});
       }
    }, [dispatch]);

    const handleClose = (event: React.SyntheticEvent | React.MouseEvent, reason?: string) => {
        if (reason === 'clickaway') {
          return;
        }
        dispatch({type: MetamaskActions.SET_INSTALLED_STATUS, payload: false})
      };
    
    const shouldDisplaySnackbar = (): boolean => {
      if (!state.polkadotSnap.isInstalled && state.polkadotSnap.message) return true;
      else return false;
    }

    return(
        <div>
            <Snackbar
                anchorOrigin={{
                    vertical: 'bottom',
                    horizontal: 'left',
                }}
                open={shouldDisplaySnackbar()}
                autoHideDuration={6000}
                onClose={handleClose}
                message={state.polkadotSnap.message}
                action={
                    <React.Fragment>
                      <IconButton size="small" aria-label="close" color="inherit" onClick={handleClose}>
                        <CloseIcon fontSize="small" />
                      </IconButton>
                    </React.Fragment>
                  }
            />
            <Hidden xsUp={state.hasMetaMask}>
                <Alert severity="warning">Ensure that MetaMask is installed!</Alert>
                <Box mt={"1rem"} />
            </Hidden>
            <Button
                disabled={!state.hasMetaMask}
                onClick={installSnap}
                variant="contained"
                size={"large"}
                color="primary"
            >
                Connect to MetaMask
            </Button>
        </div>
    );

}
Example #29
Source File: MonitoringCard.tsx    From Pi-Tool with GNU General Public License v3.0 5 votes vote down vote up
MonitoringCard: React.FC = () => {
    const [open, setOpen] = React.useState(false);
    const metrics = useSelector((state: RootState) => state.monitoring.activeMetrics);

    const handleOpen = () => { setOpen(true); }
    const handleClose = () => { setOpen(false); }

    const cardActions = (
        <Box>
            <Tooltip title="Select metrics" placement="left">
                <IconButton aria-label="delete" color="default" onClick={handleOpen}>
                    <SettingsIcon />
                </IconButton>
            </Tooltip>
        </Box>
    );

    const activeMetrics = Object.keys(metrics)
        .filter(m => metrics[m as MonitoringMetric].active);

    const computeChartWidth = (len: number, idx: number) => {
        if (len > 1) {
            return (((idx % 2) === 0) && (idx === len - 1) ? '100%' : '50%');
        } else {
            return '100%';
        }
    }

    const charts = activeMetrics.map((metric, index) => (
        <Box width={computeChartWidth(activeMetrics.length, index)}>
            <MetricChart metric={metric as MonitoringMetric} key={`chart-${metric as string}`} />
        </Box>
    ));

    const noSelected = (charts.length === 0) && (
        <Box display="flex" justifyContent="center">
            <Typography>No metric selected.</Typography>
        </Box>
    );

    return (
        <MainCard title="Monitoring" actions={cardActions}>
            <MonitoringDialog open={open} onClose={handleClose} />
            <Box display="flex" flexWrap="wrap" width="100%" p={1}>
                {charts}
            </Box>

            {noSelected}
        </MainCard>
    );
}