@material-ui/core#Snackbar JavaScript Examples

The following examples show how to use @material-ui/core#Snackbar. 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: SnackbarAlert.js    From lrc-staking-dapp with MIT License 7 votes vote down vote up
SnackbarAlert = React.memo(({
  isOpen, children, severity, onClose,
}) => (
  <Snackbar
    open={!!isOpen}
    ClickAwayListenerProps={{ onClickAway: onClose }}
    onClose={onClose}
    anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
  >
    <MuiAlert className="mb-4" severity={severity}>
      <div className="d-flex align-items-center align-content-center">
        <span>
          {children}
        </span>
      </div>
    </MuiAlert>
  </Snackbar>
))
Example #2
Source File: ToolbarExtension.js    From eSim-Cloud with GNU General Public License v3.0 6 votes vote down vote up
function SimpleSnackbar ({ open, close, message }) {
  return (
    <div>
      <Snackbar
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left'
        }}
        open={open}
        autoHideDuration={4000}
        onClose={close}
        message={message}
        action={
          <React.Fragment>
            <IconButton size="small" aria-label="close" color="inherit" onClick={close}>
              <CloseIcon fontSize="small" />
            </IconButton>
          </React.Fragment>
        }
      />
    </div>
  )
}
Example #3
Source File: SchematicToolbar.js    From eSim-Cloud with GNU General Public License v3.0 6 votes vote down vote up
// Notification snackbar to give alert messages
function SimpleSnackbar ({ open, close, message }) {
  return (
    <div>
      <Snackbar
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left'
        }}
        open={open}
        autoHideDuration={5000}
        onClose={close}
        message={message}
        action={
          <React.Fragment>
            <IconButton
              size="small"
              aria-label="close"
              color="inherit"
              onClick={close}
            >
              <CloseIcon fontSize="small" />
            </IconButton>
          </React.Fragment>
        }
      />
    </div>
  )
}
Example #4
Source File: Header.js    From eSim-Cloud with GNU General Public License v3.0 6 votes vote down vote up
// Notification snackbar to give alert messages
function SimpleSnackbar ({ open, close, message }) {
  return (
    <div>
      <Snackbar
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left'
        }}
        open={open}
        autoHideDuration={6000}
        onClose={close}
        message={message}
        action={
          <React.Fragment>
            <IconButton size="small" aria-label="close" color="inherit" onClick={close}>
              <CloseIcon fontSize="small" />
            </IconButton>
          </React.Fragment>
        }
      />
    </div>
  )
}
Example #5
Source File: Alert.js    From web-wallet with Apache License 2.0 6 votes vote down vote up
function _Alert ({ children, open, onClose, type = 'success', duration = 3000 }) {
  function Alert (props) {
    return <MuiAlert elevation={6} variant='filled' {...props} />;
  }

  return (
    <Snackbar
      open={open}
      autoHideDuration={duration ? duration : undefined}
      onClose={onClose}
      anchorOrigin={{
        vertical: 'top',
        horizontal: 'center'
      }}
    >
      <Alert onClose={onClose} severity={type}>
        {children}
      </Alert>
    </Snackbar>
  );
}
Example #6
Source File: CopyNotification.js    From treetracker-admin-client with GNU Affero General Public License v3.0 6 votes vote down vote up
CopyNotification = (props) => {
  const { snackbarLabel, snackbarOpen, setSnackbarOpen } = props;

  function handleSnackbarClose(event, reason) {
    if (reason === 'clickaway') {
      return;
    }
    setSnackbarOpen(false);
  }

  return (
    <>
      <Snackbar
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
        key={snackbarLabel.length ? snackbarLabel : undefined}
        open={snackbarOpen}
        autoHideDuration={2000}
        onClose={handleSnackbarClose}
        message={`${snackbarLabel} copied to clipboard`}
        color="primary"
        action={
          <>
            <IconButton
              size="small"
              aria-label="close"
              onClick={handleSnackbarClose}
            >
              <CloseIcon fontSize="small" />
            </IconButton>
          </>
        }
      />
    </>
  );
}
Example #7
Source File: SnackBar.js    From Octave with MIT License 6 votes vote down vote up
// This is the small Notification popup that appear on the Bottom of the page
function SnackBar({ setSnackBar, snackBar }) {
  const closeSnackBar = () => {
    setSnackBar(null);
  };

  return (
    <Snackbar
      anchorOrigin={{
        vertical: "bottom",
        horizontal: "left",
      }}
      open={Boolean(snackBar)} // snackBar will be a message so ,its being converted into a Boolean
      onClose={closeSnackBar}
      autoHideDuration={3000}
      message={snackBar} // Actual Message
      action={
        <IconButton
          size="small"
          aria-label="close"
          color="inherit"
          onClick={closeSnackBar}
        >
          <CloseIcon fontSize="small" />
        </IconButton>
      }
    />
  );
}
Example #8
Source File: NotificationContext.js    From ehr with GNU Affero General Public License v3.0 6 votes vote down vote up
render() {
        const { feedback } = this.state;
        const { classes } = this.props;
        return (
            <NotificationContext.Provider
                value={{
                    showNotification: this.showNotification,
                }}
            >
                {this.props.children}

                <Snackbar
                    open={this.state.isSnackbarOpen}
                    className={classes.feedbackMessage}
                    autoHideDuration={5000}
                    onClose={this.closeNotification}
                    anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
                >
                    <Alert severity={feedback.severity} className="feedbackMessage" onClose={this.closeNotification}>
                        {feedback.message}
                    </Alert>
                </Snackbar>
            </NotificationContext.Provider>
        );
    }
Example #9
Source File: ToastNotif.js    From reddish with MIT License 6 votes vote down vote up
ToastNotif = () => {
  const dispatch = useDispatch();
  const notification = useSelector((state) => state.notification);

  if (!notification) {
    return null;
  }

  const { message, severity } = notification;

  const handleNotifClose = () => {
    dispatch(clearNotif());
  };

  return (
    <Snackbar
      open={!!notification}
      onClose={handleNotifClose}
      anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
    >
      <Alert onClose={handleNotifClose} severity={severity}>
        {message}
      </Alert>
    </Snackbar>
  );
}
Example #10
Source File: ToastNotification.js    From stack-underflow with MIT License 6 votes vote down vote up
ToastNotification = () => {
  const { notification, clearNotif } = useStateContext();

  if (!notification?.message) {
    return null;
  }

  const { message, severity } = notification;

  return (
    <Snackbar
      open={!!notification}
      onClose={() => clearNotif()}
      anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
    >
      <Alert onClose={() => clearNotif()} severity={severity}>
        {message}
      </Alert>
    </Snackbar>
  );
}
Example #11
Source File: ToastNotify.js    From to-view-list with MIT License 6 votes vote down vote up
ToastNotify = ({ open, handleClose, severity, message }) => {
  const duration = 5;

  return (
    <Snackbar
      open={open}
      autoHideDuration={duration * 1000}
      onClose={handleClose}
      anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
    >
      <Alert onClose={handleClose} severity={severity}>
        {message}
      </Alert>
    </Snackbar>
  );
}
Example #12
Source File: Snackbar.js    From inventory-management-web with MIT License 5 votes vote down vote up
SimpleSnackbar = () => {
  const { snack, setSnack } = useContext(SnackContext);
  const { open, message, action, actionParams, type } = snack;

  const history = useHistory();

  const handleAction = () => {
    if (action === 'EDIT') {
      history.push('/updateproduct', {
        name: actionParams.name,
        sellingPrice: actionParams.sellingPrice,
        loose: actionParams.loose,
        id: actionParams.id,
      });
    }
    setSnack(prevState => ({ ...prevState, open: false }));
  };

  const handleClose = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }

    setSnack(prevState => ({ ...prevState, open: false }));
  };

  return (
    <div>
      <Snackbar
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'center',
        }}
        open={open}
        autoHideDuration={6000}
        onClose={handleClose}
      >
        <Alert
          variant='filled'
          elevation={6}
          severity={type}
          onClose={handleClose}
          action={
            // eslint-disable-next-line react/jsx-wrap-multilines
            <>
              {action === '' ? null : (
                <Button color='inherit' size='small' onClick={handleAction}>
                  {action}
                </Button>
              )}

              <IconButton
                size='small'
                aria-label='close'
                color='inherit'
                onClick={handleClose}
              >
                <CloseIcon fontSize='small' />
              </IconButton>
            </>
          }
        >
          {message}
        </Alert>
      </Snackbar>
    </div>
  );
}
Example #13
Source File: update.jsx    From redive_linebot with MIT License 5 votes vote down vote up
WorldbossMessageUpdate = () => {
  const { id } = useParams();
  const [errorControl, setError] = useState({ show: false, message: "" });
  const [{ data, loading }] = useAxios(`/api/Game/World/Boss/Feature/Message/${id}`);
  const [{ data: updateData, loading: updateLoading, error: updateError }, update] = useAxios(
    {
      url: `/api/Game/World/Boss/Feature/Message/${id}`,
      method: "PUT",
    },
    { manual: true }
  );

  const onSubmit = formData => {
    const { data = {}, isValidImage = false, isValidTemplate = false } = formData;
    const { template, imageUrl } = data;

    if (isValidImage && isValidTemplate) {
      const payload = { template };
      if (imageUrl) {
        payload.icon_url = imageUrl;
      }
      update({
        data: payload,
      });
    } else {
      setError({ show: true, message: "Invalid form data" });
    }
  };

  useEffect(() => {
    if (updateError) {
      setError({ show: true, message: updateError.message });
    }
  }, [updateError]);

  if (loading) return <div>Loading...</div>;

  // 如果成功,就導回列表頁
  if (updateData && updateData.message === "success") {
    return <Redirect to="/Admin/WorldbossMessage" />;
  }

  const message = data?.data;
  const { icon_url, template } = message;

  return (
    <Grid container direction="column" spacing={1}>
      <Grid item>
        <MessageForm
          defaultImageUrl={icon_url}
          defaultTemplate={template}
          onSubmit={onSubmit}
          loading={updateLoading || loading}
        />
      </Grid>
      <Snackbar
        open={errorControl.show}
        autoHideDuration={6000}
        onClose={() => setError({ ...errorControl, show: false })}
      >
        <Alert elevation={6} variant="filled" severity="error" style={{ width: "100%" }}>
          {errorControl.message}
        </Alert>
      </Snackbar>
    </Grid>
  );
}
Example #14
Source File: App.js    From Interceptor with MIT License 5 votes vote down vote up
render() {
    //console.log("Rendering App");
    const { classes } = this.props;
    return (
      <>
        <ThemeProvider theme={this.theme}>
          <CssBaseline />
          <WebSocketHelper
            ws_url={this.state.ws_url}
            messageProcess={this.messageProcess}
            ref={this.wshelper}
            status={status => this.ws_status = status}
          />
          <AppBar position="sticky" color="default">
            <Toolbar>
              <Tabs
                className={classes.mainTabs}
                value={this.state.selectedTab}
                onChange={(event, newValue) => this.setState({ selectedTab: newValue })}
                indicatorColor="secondary"
                textColor="inherit"
                variant="scrollable"
                scrollButtons="auto"
                aria-label="Plugins tabs"
              >
                <Tab label="Dashboard" disabled {...this.a11yProps(0)} />
                <Tab label="Graphs" {...this.a11yProps(1)} />
                <Tab label="Joystick" {...this.a11yProps(2)} />
                <Tab label="OP Edit" {...this.a11yProps(3)} />
                <Tab label="CAN BUS" disabled {...this.a11yProps(4)} />
              </Tabs>

              {this.connectionStatus()}
              <IconButton onClick={() => { this.setState({ show_mainsettings: true }) }} aria-label="WebSocket connection status" component="span" color="inherit">
                <SettingsIcon />
              </IconButton>
            </Toolbar>
          </AppBar>

          <TabPanel value={this.state.selectedTab} index={0}>
            Dashboard will be here
          </TabPanel>
          <TabPanel value={this.state.selectedTab} index={1}>
            <GraphDashboard ref={this.pushgraphdata} active={this.state.selectedTab === 1} />
          </TabPanel>
          <TabPanel value={this.state.selectedTab} index={2}>
            <Joystick procData={data => this.sendWSmsg(data)} active={this.state.selectedTab === 2} />
          </TabPanel>
          <TabPanel value={this.state.selectedTab} index={3}>
            <OPEdit ref={this.pushopedit} procData={data => this.sendWSmsg(data)} active={this.state.selectedTab === 3} />
          </TabPanel>
          <TabPanel value={this.state.selectedTab} index={4}>
            CAN messages will be here
          </TabPanel>
          {this.state.show_mainsettings ? (
            <MainSettings
              setSettings={(ws_url, rate, dark_theme) => { this.setState({ show_mainsettings: false, ws_url: ws_url, rateHz: rate }); this.setTheme(dark_theme) }}
              show={this.state.show_mainsettings}
              ws_url={this.state.ws_url}
              rateHz={this.state.rateHz}
              dark_theme={this.state.dark_theme}
            />
          ) : (null)}
          <Snackbar
            anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
            open={this.show_error}
            autoHideDuration={5000}
            onClose={() => this.show_error = false}
          >
            <MuiAlert elevation={6} variant="filled" severity="error">{this.last_error_msg}</MuiAlert>
          </Snackbar>
        </ThemeProvider>
      </>
    );
  }
Example #15
Source File: create.jsx    From redive_linebot with MIT License 5 votes vote down vote up
WorldbossMessageCreate = () => {
  const [{ data, loading, error }, sendRequest] = useAxios(
    {
      url: "/api/Game/World/Boss/Feature/Message",
      method: "POST",
    },
    { manual: true }
  );
  const [errorControl, setError] = useState({ show: false, message: "" });

  const onSubmit = formData => {
    const { data = {}, isValidImage = false, isValidTemplate = false } = formData;
    const { template, imageUrl } = data;

    if (isValidImage && isValidTemplate) {
      const payload = { template };
      if (imageUrl) {
        payload.icon_url = imageUrl;
      }
      sendRequest({
        data: payload,
      });
    } else {
      setError({ show: true, message: "Invalid form data" });
    }
  };

  useEffect(() => {
    if (error) {
      setError({ show: true, message: error.message });
    }
  }, [error]);

  // 如果成功,就導回列表頁
  if (data && data.message === "success") {
    return <Redirect to="/Admin/WorldbossMessage" />;
  }

  return (
    <Grid container direction="column" spacing={1}>
      <Grid item>
        <Alert severity="warning">
          請注意,此訊息建立後,將立即生效,所有玩家將會馬上注意到此訊息的內容。
        </Alert>
      </Grid>
      <Grid item>
        <MessageForm onSubmit={onSubmit} loading={loading} />
      </Grid>
      <Snackbar
        open={errorControl.show}
        autoHideDuration={6000}
        onClose={() => setError({ ...errorControl, show: false })}
      >
        <Alert elevation={6} variant="filled" severity="error" style={{ width: "100%" }}>
          {errorControl.message}
        </Alert>
      </Snackbar>
    </Grid>
  );
}
Example #16
Source File: Snackbar.js    From eSim-Cloud with GNU General Public License v3.0 5 votes vote down vote up
// Schematic delete snackbar

export default function SimpleSnackbar ({ open, close, sch, confirmation }) {
  const dispatch = useDispatch()

  return (
    <Snackbar
      anchorOrigin={{
        vertical: 'bottom',
        horizontal: 'center'
      }}
      open={open}
      autoHideDuration={6000}
      onClose={close}
    >
      <Alert
        icon={false}
        severity="warning"
        color="error"
        style={{ width: '100%' }}
        action={
          <>
            <Button
              size="small"
              aria-label="close"
              color="inherit"
              onClick={() => {
                dispatch(confirmation(sch.save_id))
              }}
            >
              Yes
            </Button>
            <Button
              size="small"
              aria-label="close"
              color="inherit"
              onClick={close}
            >
              NO
            </Button>
          </>
        }
      >
        {'Delete ' + sch.name + ' ?'}
      </Alert>
    </Snackbar>
  )
}
Example #17
Source File: Activation.jsx    From pwa with MIT License 4 votes vote down vote up
export default function Activation({ onBackClick, onActivate }) {
  const ttl = useSelector((store) => store.MyActivities.ttl);
  const phone = useSelector((store) => store.MyActivities.phone);
  const condition = useSelector((store) => store.MyActivities.condition);

  const { i: countdown, start } = useTimer({ start: ttl });

  const [code, setCode] = useState('');
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [smsSent, setSmsSent] = useState(false);

  const [isAlertOpen, setIsAlertOpen] = useState(false);
  const [alertText, setAlertText] = useState('');

  useEffect(() => {
    start();
    /*eslint-disable-next-line react-hooks/exhaustive-deps*/
  }, []);

  function sendActivationSMS() {
    setIsDialogOpen(true);
    axios({
      method: 'POST',
      url: `${process.env.REACT_APP_REGISTER_USER_AGAIN}`,
      data: {
        phone_number: phone,
        risk_group: condition,
      },
    })
      .then(() => {
        setIsDialogOpen(false);
        setSmsSent(true);
      })
      .catch((err) => {
        console.error(err);
        setAlertText('ارسال کد با خطا مواجه شد!');
        setIsAlertOpen(true);
        setIsDialogOpen(false);
      });
  }

  function onSubmit() {
    setIsDialogOpen(true);
    axios({
      method: 'POST',
      url: `${process.env.REACT_APP_ACTIVATE_USER}`,
      data: {
        phone_number: phone,
        code: perToEngDigits(code),
      },
    })
      .then(({ data }) => {
        setIsDialogOpen(false);
        onActivate({
          token: data.access_token,
          user: data.user,
        });
      })
      .catch((err) => {
        console.error(err);
        setAlertText('کد واردشده اشتباه است!');
        setIsAlertOpen(true);
        setIsDialogOpen(false);
      });
  }

  return (
    <>
      <AppBar position="static" className="activity-header">
        <Toolbar>
          <img src={logo} className="app-header-logo" alt="logo" />
          <IconButton color="inherit" onClick={onBackClick}>
            <KeyboardBackspace />
          </IconButton>
        </Toolbar>
      </AppBar>
      <div className={styles.container}>
        {/* #FIXME Use formattedMessage */}
        <Typography align="center">
          کد فعال‌سازی ۵ رقمی که برای شما پیامک شد را وارد کنید.
        </Typography>
        <Box mt={2} textAlign="center">
          <Button color="primary" onClick={onBackClick}>
            <div>{phone}</div>
            <Edit className={styles.editIcon} fontSize="small" />
          </Button>
        </Box>
        <Box mt={4}>
          <TextField
            label="کد فعال‌سازی"
            value={code}
            onChange={(e) => setCode(e.target.value)}
            fullWidth
          />
        </Box>
        <Box mt={3} textAlign="center">
          <Button
            variant="contained"
            color="primary"
            size="large"
            className="activation-btn"
            onClick={onSubmit}
          >
            فعال‌سازی
          </Button>
        </Box>
        <Box mt={3}>
          <Typography color="primary" align="center">
            {`فرصت باقی مانده برای ورود: ${Math.floor(countdown / 60)}:${
              countdown % 60
            }`}
          </Typography>
        </Box>
        {!smsSent && (
          <Box mt={2} textAlign="center">
            <Button color="primary" onClick={sendActivationSMS}>
              ارسال مجدد کد فعال‌سازی
            </Button>
          </Box>
        )}
      </div>
      <Dialog open={isDialogOpen}>
        <div className={styles.dialogContent}>
          <CircularProgress />
          <Box ml={3}>{'لطفا کمی صبر کنید.'}</Box>
        </div>
      </Dialog>
      <Snackbar
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'center',
        }}
        open={isAlertOpen}
        autoHideDuration={5000}
        onClose={() => setIsAlertOpen(false)}
        message={alertText}
      />
    </>
  );
}
Example #18
Source File: ProjectPage.js    From eSim-Cloud with GNU General Public License v3.0 4 votes vote down vote up
export default function ProjectPage (props) {
  const classes = useStyles()
  const gridRef = React.createRef()
  const dispatch = useDispatch()
  const [netListOpen, setNetListOpen] = React.useState(false)
  const [snackbarOpen, setSnackbarOpen] = React.useState(false)
  const [simulateOpen, setSimulateOpen] = React.useState(false)
  const [reportOpen, setReportOpen] = React.useState(false)
  const [reportDescription, setDescription] = React.useState(null)
  const [netlist, genNetlist] = React.useState('')
  const [statusChanged, setStatusChanged] = React.useState(false)
  const [componentsList, setComponentsList] = React.useState(undefined)
  const project = useSelector(state => state.projectReducer)
  const auth = useSelector(state => state.authReducer)
  const netfile = useSelector((state) => state.netlistReducer)
  const DialogTitle = withStyles(styles)((props) => {
    const { children, classes, onClose, ...other } = props
    return (
      <MuiDialogTitle disableTypography className={classes.root} {...other}>
        <Typography variant="h6">{children}</Typography>
        {onClose ? (
          <IconButton aria-label="close" className={classes.closeButton} onClick={onClose}>
            <CloseIcon />
          </IconButton>
        ) : null}
      </MuiDialogTitle>
    )
  })
  const handleSimulateOpen = () => {
    setSimulateOpen(!simulateOpen)
  }
  const handleReportOpen = () => {
    setReportOpen(!reportOpen)
  }
  const handleChangeDescription = (e) => {
    setDescription(e.target.value)
  }
  const handleNetlistClick = () => {
    setNetListOpen(!netListOpen)
  }
  const onClick = (type) => {
    const query = new URLSearchParams(props.location.search)
    var save_id = query.get('save_id')
    var project_id = query.get('project_id')
    switch (type) {
      case 'Report':
        dispatch(reportProject(reportDescription, project_id))
        handleReportOpen()
        break
      case 'Make copy':
        dispatch(makeCopy(save_id, project.details.active_version, project.details.active_branch))
        setSnackbarOpen(true)
        break
      case 'Generate Netlist':
        var compNetlist = GenerateNetList()
        var netlist =
          netfile.title +
          '\n\n' +
          compNetlist.models +
          '\n' +
          compNetlist.main +
          '\n' +
          netfile.controlLine +
          '\n' +
          netfile.controlBlock +
          '\n'
        genNetlist(netlist)
        handleNetlistClick()
        break
      default:
        break
    }
  }
  const changedStatus = () => {
    setStatusChanged(true)
  }
  useEffect(() => {
    console.log(project.details)
  }, [project])
  useEffect(() => {
    var container = gridRef.current
    LoadGrid(container, null, null)
    if (props.location.search !== '') {
      const query = new URLSearchParams(props.location.search)
      var saveID = query.get('save_id')
      var version = query.get('version')
      var branch = query.get('branch')
      if (saveID.substr(0, 7) === 'gallery') {
        // Loading Gallery schemaic.
        dispatch(fetchGallerySchematic(saveID))
      } else {
        // Loading User on-cloud saved schemaic.
        dispatch(fetchSchematic(saveID, version, branch))
      }
    }
    setTimeout(() => {
      setComponentsList([GenerateDetailedCompList()])
    }, 2000)
    // eslint-disable-next-line
  }, [props.location, dispatch])
  return (
    <div className={classes.root}>
      <LayoutMain>

        {project.details !== '401'
          ? <>
            {statusChanged
              ? <>
                Status Changed
              </> : <Grid container>
                <Grid item xs={1} />
                <Grid item xs={10}>
                  {project.reports && project.details.is_reported &&
                    <ReportComponent project={project} changedStatus={changedStatus} location={props.location} />
                  }
                  {project.details && !project.details?.is_reported && project.details?.author_name !== auth.user?.username &&
                    <ChangeStatus project={project} changedStatus={changedStatus} />
                  }
                  <Paper style={{ padding: '1%', marginTop: '2%', borderRadius: '12px' }}>
                    <Typography>
                      {project.details && <h1 style={{ marginTop: '0', marginBottom: '0' }}>{project.details.title}</h1>}
                      {project.details && <h4 style={{ marginTop: '0', marginBottom: '0' }}>By: {project.details.author_name} </h4>}
                    </Typography>
                    <hr style={{ marginTop: '0' }} />

                    <Typography>
                      <h3>{project.details?.description}</h3>
                      {componentsList && <h2 style={{ marginBottom: '0' }}>Component List:</h2>}
                      {componentsList && componentsList[0].map((item, i) => (<div key={i}>{i + 1}.{item.name}  {item.value}{item.unit}</div>))}
                      {project.details && project.details?.fields && project.details.fields.map(item => (
                        <p key={item}>
                          <h3 style={{ marginTop: '0', marginBottom: '0' }}>{item.name}:</h3>
                          <p style={{ marginTop: '0' }}>
                            {item.text.split('\n').map((text) => (
                              <span key={text}>
                                {text}
                                <br></br>
                              </span>
                            ))}
                          </p>
                        </p>
                      ))}
                    </Typography>

                    <Dialog
                      open={simulateOpen}
                      onClose={handleSimulateOpen}
                    >
                      <DialogTitle onClose={handleSimulateOpen}>Simulate Circuit</DialogTitle>
                      <DialogContent style={{ padding: '3%' }}>
                        {project.details && <SimulationProperties
                          dcSweepcontrolLine={project.details.dc_sweep}
                          transientAnalysisControlLine={project.details.transient_analysis}
                          acAnalysisControlLine={project.details.ac_analysis}
                          tfAnalysisControlLine={project.details.tf_analysis}
                        />}
                      </DialogContent>
                    </Dialog>
                    <Dialog
                      open={reportOpen}
                      onClose={handleReportOpen}
                      fullWidth={true}
                      maxWidth={'md'} >
                      <DialogTitle>Report this project</DialogTitle>
                      <DialogContent style={{ padding: '3%' }}>
                        <TextField
                          multiline
                          variant="outlined"
                          label="Report Description"
                          style={{ width: '100%' }}
                          value={reportDescription}
                          error={!reportDescription}
                          helperText={'Please enter description'}
                          onChange={handleChangeDescription}
                          rows={8} />
                      </DialogContent>
                      <DialogActions>
                        <Button onClick={() => onClick('Report')}>Report</Button>
                        <Button onClick={handleReportOpen}>Cancel</Button>
                      </DialogActions>
                    </Dialog>
                  </Paper>
                  <h1>Circuit Diagram:
                    {auth.isAuthenticated && <Button variant="contained" style={{ float: 'right', backgroundColor: 'red', color: 'white', marginTop: '.5%' }} onClick={() => handleReportOpen()}>Report</Button>}
                    {auth.isAuthenticated && <Button variant="contained" color="primary" style={{ float: 'right', margin: '.5% .5% 0 0%' }} onClick={() => onClick('Make copy')}>Make a Copy</Button>}
                    <Button style={{ float: 'right', backgroundColor: 'lightgreen', margin: '.5% .5% 0 0' }} variant="contained" onClick={() => handleSimulateOpen()}>
                      <PlayCircleOutlineIcon />Simulate
                    </Button>
                    <Button variant="contained" color="primary" style={{ float: 'right', margin: '.5% .5% 0 0%' }} onClick={() => onClick('Generate Netlist')}>Generate Netlist</Button>
                  </h1>
                  <NetlistModal open={netListOpen} close={handleNetlistClick} netlist={netlist} />
                  <Snackbar
                    open={snackbarOpen}
                    autoHideDuration={6000}
                    onClose={() => setSnackbarOpen(false)}
                  >
                    <Alert onClose={() => setSnackbarOpen(false)} severity="success">
                      Successfully made a copy!
                    </Alert>
                  </Snackbar>
                  <Grid container>
                    <Grid item xs={1}>
                      <Paper style={{ width: '30px' }}>
                        <div>
                          <Tooltip title="Zoom In">
                            <IconButton color="inherit" className={classes.tools} size="small" onClick={ZoomIn}>
                              <ZoomInIcon />
                            </IconButton>
                          </Tooltip>
                        </div>
                        <div>
                          <Tooltip title="Zoom Out">
                            <IconButton color="inherit" className={classes.tools} size="small" onClick={ZoomOut}>
                              <ZoomOutIcon />
                            </IconButton>
                          </Tooltip>
                        </div>
                        <div>
                          <Tooltip title="Default Size">
                            <IconButton color="inherit" className={classes.tools} size="small" onClick={ZoomAct}>
                              <SettingsOverscanIcon />
                            </IconButton>
                          </Tooltip>
                        </div>
                      </Paper>
                    </Grid>
                    <Grid item xs={10}>
                      <LayoutMain>
                        <center>
                          <div className="grid-container A4-L" ref={gridRef} id="divGrid" />
                        </center>
                      </LayoutMain>
                    </Grid>
                    <ComponentProperties />
                    <Grid item xs={1} />

                    <Grid item xs={12} sm={12}>
                      <Paper style={{ padding: '0 2%', margin: '3% 0', borderRadius: '12px' }}>
                        <List>
                          <h3>History of this Project</h3>
                          {project.details?.history[0]
                            ? <ProjectTimeline history={project.details.history.slice(0).reverse()} isOwner={auth.user?.username === project.details.author_name} />
                            : <h4>No history of this project.</h4>
                          }
                        </List>
                      </Paper>
                    </Grid>
                  </Grid>
                </Grid>
                <Grid item xs={1} />
              </Grid>}
          </>
          : <>
            {statusChanged ? <>Status Changed. Wait for it to get back to the status where it is visible for you.</> : <>Not Authorized</>}
          </>}
      </LayoutMain>
    </div>
  )
}
Example #19
Source File: Contacts.js    From developer-portfolio with Apache License 2.0 4 votes vote down vote up
function Contacts() {
    const [open, setOpen] = useState(false);

    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [message, setMessage] = useState('');

    const [success, setSuccess] = useState(false);
    const [errMsg, setErrMsg] = useState('');

    const { theme } = useContext(ThemeContext);

    const handleClose = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }

        setOpen(false);
    };

    const useStyles = makeStyles((t) => ({
        input: {
            border: `4px solid ${theme.primary80}`,
            backgroundColor: `${theme.secondary}`,
            color: `${theme.tertiary}`,
            fontFamily: 'var(--primaryFont)',
            fontWeight: 500,
            transition: 'border 0.2s ease-in-out',
            '&:focus': {
                border: `4px solid ${theme.primary600}`,
            },
        },
        message: {
            border: `4px solid ${theme.primary80}`,
            backgroundColor: `${theme.secondary}`,
            color: `${theme.tertiary}`,
            fontFamily: 'var(--primaryFont)',
            fontWeight: 500,
            transition: 'border 0.2s ease-in-out',
            '&:focus': {
                border: `4px solid ${theme.primary600}`,
            },
        },
        label: {
            backgroundColor: `${theme.secondary}`,
            color: `${theme.primary}`,
            fontFamily: 'var(--primaryFont)',
            fontWeight: 600,
            fontSize: '0.9rem',
            padding: '0 5px',
            transform: 'translate(25px,50%)',
            display: 'inline-flex',
        },
        socialIcon: {
            width: '45px',
            height: '45px',
            borderRadius: '50%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '21px',
            backgroundColor: theme.primary,
            color: theme.secondary,
            transition: '250ms ease-in-out',
            '&:hover': {
                transform: 'scale(1.1)',
                color: theme.secondary,
                backgroundColor: theme.tertiary,
            },
        },
        detailsIcon: {
            backgroundColor: theme.primary,
            color: theme.secondary,
            borderRadius: '50%',
            width: '45px',
            height: '45px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '23px',
            transition: '250ms ease-in-out',
            flexShrink: 0,
            '&:hover': {
                transform: 'scale(1.1)',
                color: theme.secondary,
                backgroundColor: theme.tertiary,
            },
        },
        submitBtn: {
            backgroundColor: theme.primary,
            color: theme.secondary,
            transition: '250ms ease-in-out',
            '&:hover': {
                transform: 'scale(1.08)',
                color: theme.secondary,
                backgroundColor: theme.tertiary,
            },
        },
    }));

    const classes = useStyles();

    const handleContactForm = (e) => {
        e.preventDefault();

        if (name && email && message) {
            if (isEmail(email)) {
                const responseData = {
                    name: name,
                    email: email,
                    message: message,
                };

                axios.post(contactsData.sheetAPI, responseData).then((res) => {
                    console.log('success');
                    setSuccess(true);
                    setErrMsg('');

                    setName('');
                    setEmail('');
                    setMessage('');
                    setOpen(false);
                });
            } else {
                setErrMsg('Invalid email');
                setOpen(true);
            }
        } else {
            setErrMsg('Enter all the fields');
            setOpen(true);
        }
    };

    return (
        <div
            className='contacts'
            id='contacts'
            style={{ backgroundColor: theme.secondary }}
        >
            <div className='contacts--container'>
                <h1 style={{ color: theme.primary }}>Contacts</h1>
                <div className='contacts-body'>
                    <div className='contacts-form'>
                        <form onSubmit={handleContactForm}>
                            <div className='input-container'>
                                <label htmlFor='Name' className={classes.label}>
                                    Name
                                </label>
                                <input
                                    placeholder='John Doe'
                                    value={name}
                                    onChange={(e) => setName(e.target.value)}
                                    type='text'
                                    name='Name'
                                    className={`form-input ${classes.input}`}
                                />
                            </div>
                            <div className='input-container'>
                                <label
                                    htmlFor='Email'
                                    className={classes.label}
                                >
                                    Email
                                </label>
                                <input
                                    placeholder='[email protected]'
                                    value={email}
                                    onChange={(e) => setEmail(e.target.value)}
                                    type='email'
                                    name='Email'
                                    className={`form-input ${classes.input}`}
                                />
                            </div>
                            <div className='input-container'>
                                <label
                                    htmlFor='Message'
                                    className={classes.label}
                                >
                                    Message
                                </label>
                                <textarea
                                    placeholder='Type your message....'
                                    value={message}
                                    onChange={(e) => setMessage(e.target.value)}
                                    type='text'
                                    name='Message'
                                    className={`form-message ${classes.message}`}
                                />
                            </div>

                            <div className='submit-btn'>
                                <button
                                    type='submit'
                                    className={classes.submitBtn}
                                >
                                    <p>{!success ? 'Send' : 'Sent'}</p>
                                    <div className='submit-icon'>
                                        <AiOutlineSend
                                            className='send-icon'
                                            style={{
                                                animation: !success
                                                    ? 'initial'
                                                    : 'fly 0.8s linear both',
                                                position: success
                                                    ? 'absolute'
                                                    : 'initial',
                                            }}
                                        />
                                        <AiOutlineCheckCircle
                                            className='success-icon'
                                            style={{
                                                display: !success
                                                    ? 'none'
                                                    : 'inline-flex',
                                                opacity: !success ? '0' : '1',
                                            }}
                                        />
                                    </div>
                                </button>
                            </div>
                        </form>
                        <Snackbar
                            anchorOrigin={{
                                vertical: 'top',
                                horizontal: 'center',
                            }}
                            open={open}
                            autoHideDuration={4000}
                            onClose={handleClose}
                        >
                            <SnackbarContent
                                action={
                                    <React.Fragment>
                                        <IconButton
                                            size='small'
                                            aria-label='close'
                                            color='inherit'
                                            onClick={handleClose}
                                        >
                                            <CloseIcon fontSize='small' />
                                        </IconButton>
                                    </React.Fragment>
                                }
                                style={{
                                    backgroundColor: theme.primary,
                                    color: theme.secondary,
                                    fontFamily: 'var(--primaryFont)',
                                }}
                                message={errMsg}
                            />
                        </Snackbar>
                    </div>

                    <div className='contacts-details'>
                        <a
                            href={`mailto:${contactsData.email}`}
                            className='personal-details'
                        >
                            <div className={classes.detailsIcon}>
                                <FiAtSign />
                            </div>
                            <p style={{ color: theme.tertiary }}>
                                {contactsData.email}
                            </p>
                        </a>
                        <a
                            href={`tel:${contactsData.phone}`}
                            className='personal-details'
                        >
                            <div className={classes.detailsIcon}>
                                <FiPhone />
                            </div>
                            <p style={{ color: theme.tertiary }}>
                                {contactsData.phone}
                            </p>
                        </a>
                        <div className='personal-details'>
                            <div className={classes.detailsIcon}>
                                <HiOutlineLocationMarker />
                            </div>
                            <p style={{ color: theme.tertiary }}>
                                {contactsData.address}
                            </p>
                        </div>

                        <div className='socialmedia-icons'>
                            {socialsData.twitter && (
                                <a
                                    href={socialsData.twitter}
                                    target='_blank'
                                    rel='noreferrer'
                                    className={classes.socialIcon}
                                >
                                    <FaTwitter aria-label='Twitter' />
                                </a>
                            )}
                            {socialsData.github && (
                                <a
                                    href={socialsData.github}
                                    target='_blank'
                                    rel='noreferrer'
                                    className={classes.socialIcon}
                                >
                                    <FaGithub aria-label='GitHub' />
                                </a>
                            )}
                            {socialsData.linkedIn && (
                                <a
                                    href={socialsData.linkedIn}
                                    target='_blank'
                                    rel='noreferrer'
                                    className={classes.socialIcon}
                                >
                                    <FaLinkedinIn aria-label='LinkedIn' />
                                </a>
                            )}
                            {socialsData.instagram && (
                                <a
                                    href={socialsData.instagram}
                                    target='_blank'
                                    rel='noreferrer'
                                    className={classes.socialIcon}
                                >
                                    <FaInstagram aria-label='Instagram' />
                                </a>
                            )}
                            {socialsData.medium && (
                                <a
                                    href={socialsData.medium}
                                    target='_blank'
                                    rel='noreferrer'
                                    className={classes.socialIcon}
                                >
                                    <FaMediumM aria-label='Medium' />
                                </a>
                            )}
                            {socialsData.blogger && (
                                <a
                                    href={socialsData.blogger}
                                    target='_blank'
                                    rel='noreferrer'
                                    className={classes.socialIcon}
                                >
                                    <FaBloggerB aria-label='Blogger' />
                                </a>
                            )}
                            {socialsData.youtube && (
                                <a
                                    href={socialsData.youtube}
                                    target='_blank'
                                    rel='noreferrer'
                                    className={classes.socialIcon}
                                >
                                    <FaYoutube aria-label='YouTube' />
                                </a>
                            )}
                            {socialsData.reddit && (
                                <a
                                    href={socialsData.reddit}
                                    target='_blank'
                                    rel='noreferrer'
                                    className={classes.socialIcon}
                                >
                                    <FaRedditAlien aria-label='Reddit' />
                                </a>
                            )}
                            {socialsData.stackOverflow && (
                                <a
                                    href={socialsData.stackOverflow}
                                    target='_blank'
                                    rel='noreferrer'
                                    className={classes.socialIcon}
                                >
                                    <FaStackOverflow aria-label='Stack Overflow' />
                                </a>
                            )}
                            {socialsData.codepen && (
                                <a
                                    href={socialsData.codepen}
                                    target='_blank'
                                    rel='noreferrer'
                                    className={classes.socialIcon}
                                >
                                    <FaCodepen aria-label='CodePen' />
                                </a>
                            )}
                            {socialsData.gitlab && (
                                <a
                                    href={socialsData.gitlab}
                                    target='_blank'
                                    rel='noreferrer'
                                    className={classes.socialIcon}
                                >
                                    <FaGitlab aria-label='GitLab' />
                                </a>
                            )}
                        </div>
                    </div>
                </div>
            </div>
            <img
                src={theme.contactsimg}
                alt='contacts'
                className='contacts--img'
            />
        </div>
    );
}
Example #20
Source File: active-messenger.js    From horondi_client_fe with MIT License 4 votes vote down vote up
ActiveMessenger = ({ iconsVisible, mailFormVisible }) => {
  const style = useStyles({ iconsVisible, mailFormVisible });
  const { t, i18n } = useTranslation();

  const { userData } = useSelector(({ User }) => ({
    userData: User.userData
  }));
  const defaultFirstName = get(userData, 'firstName', '');
  const defaultEmail = get(userData, 'email', '');
  const language = i18n.language === 'ua' ? 0 : 1;

  const [user, setUser] = useState({
    ...CHAT_USER_DATA,
    firstName: defaultFirstName,
    email: defaultEmail
  });
  const { firstName, email, message } = user;

  const [firstNameValidated, setFirstNameValidated] = useState(!!defaultFirstName);
  const [emailValidated, setEmailValidated] = useState(!!defaultEmail);
  const [messageValidated, setMessageValidated] = useState(false);
  const [allFieldsValidated, setAllFieldsValidated] = useState(false);
  const [shouldValidate, setShouldValidate] = useState(false);
  const [open, setOpen] = useState(false);
  const [sendEmail, { loading, error }] = useMutation(sendEmailMutation);

  const helperTextForName =
    firstName.length < TWO_LETTERS || firstName.length > THIRTY_LETTERS
      ? handleHelperText(firstNameValidated, shouldValidate, 'profile.firstName')
      : handleHelperText(firstNameValidated, shouldValidate, 'onlyLetter');

  const handleChange = (event, setValid, regExp) => {
    const input = event.target.value;
    const inputName = event.target.name;
    setUser({ ...user, [inputName]: input });
    input.match(regExp) ? setValid(true) : setValid(false);
  };

  const handleValidForms = () => {
    setShouldValidate(true);
    allFieldsValidated && sendHandler();
  };

  const handleClick = () => {
    setOpen(true);
    setUser(CHAT_USER_DATA);
  };

  const sendHandler = () => {
    setAllFieldsValidated(false);
    sendEmail({
      variables: {
        email,
        senderName: firstName,
        text: message,
        language
      }
    });
    handleClick();
  };

  const handleClose = (_event, reason) => {
    if (reason === 'clickaway') {
      return;
    }
    setOpen(false);
  };

  const Alert = (props) => <MuiAlert elevation={6} variant='filled' {...props} />;

  useEffect(() => {
    if (firstNameValidated && emailValidated && messageValidated) {
      setAllFieldsValidated(true);
    } else {
      setAllFieldsValidated(false);
    }
  }, [firstNameValidated, emailValidated, messageValidated]);

  if (loading || error) return errorOrLoadingHandler(error, loading);

  return (
    <form className={style.contactForm}>
      <span className={style.mailTitle}>{t('chat.sendMail')}</span>
      <>
        <TextField
          required
          fullWidth
          key={t('common.name')}
          label={t('common.name')}
          variant='outlined'
          name='firstName'
          size='small'
          rows={1}
          error={!firstNameValidated && shouldValidate}
          helperText={helperTextForName}
          className={style.dataInput}
          onChange={(e) => handleChange(e, setFirstNameValidated, formRegExp.firstName)}
          value={firstName}
          type='text'
        />
        <TextField
          required
          fullWidth
          key={t('common.email')}
          label={t('common.email')}
          variant='outlined'
          name='email'
          size='small'
          rows={1}
          error={!emailValidated && shouldValidate}
          helperText={handleHelperText(emailValidated, shouldValidate, 'profile.email')}
          className={style.dataInput}
          onChange={(e) => handleChange(e, setEmailValidated, formRegExp.email)}
          value={email}
          type='text'
        />
        <TextField
          fullWidth
          key={t('chat.msgText')}
          label={t('chat.msgText')}
          variant='outlined'
          name='message'
          multiline
          rows={10}
          inputProps={{ maxLength: 500 }}
          error={!messageValidated && shouldValidate}
          helperText={handleHelperText(messageValidated, shouldValidate, 'profile.message')}
          className={style.dataInput}
          onChange={(e) => handleChange(e, setMessageValidated, formRegExp.text)}
          value={message}
          type='text'
          required
        />
      </>
      <Snackbar open={open} autoHideDuration={1500} onClose={handleClose}>
        <Alert onClose={handleClose} severity='success'>
          {t('chat.thanksMsg')}
        </Alert>
      </Snackbar>
      <Button className={style.btnSend} onClick={handleValidForms}>
        {t('buttons.sendBtn')}
      </Button>
    </form>
  );
}
Example #21
Source File: SyntaxEditor.js    From SyntaxMeets with MIT License 4 votes vote down vote up
SyntaxEditor = (props) => {
  const [theme, setTheme] = useState("monokai");
  const [popup, setPopup] = useState([false, ""]);
  const [filePopup, setFilePopup] = useState(false);
  const [fileHandleError, setFileHandleError] = useState("");
  const [fullscreen,setFullscreen] = useState(false); // maintain state of screen in syntax Editor
  const [modalIsOpen,setModalIsOpen] = useState(false)
  const [shareURL,setshareURL] = useState("")
  const [isLoading,setIsLoading]=useState(false)

  // This will resend a message to update the code of the newly joined user
  useEffect(() => {
    let UpdatedCode = props.code;
    if (props.previousUser.id === props.id) {
      props.socket.emit("message", UpdatedCode);
    }
    // if the user was connected then over reloading the page this block is called
    else if(sessionStorage.getItem('isconnected'))
    {
      //it used to save the code in sessionStorage when only one user is using there in a room
      props.setCode(sessionStorage.getItem('code'));
    }
  }, [props.previousUser]);

  const classes = useStyles();
  useEffect(() => {
    props.socket.on("message", (newValue) => {
      props.setCode(newValue);
    });
  }, []);

  const handleChange = (newValue) => {
    props.setCode(newValue);
    sessionStorage.setItem('code',newValue);
    props.socket.emit("message", newValue);
  };

  const copyCode = (value) => {
    copy(value);
    setPopup([true, "Code Copied Sucessfully"]);
  };

  const fetchSharedCodeLink=async (content) =>{
    var response = await fetch("https://dpaste.com/api/v2/", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: "content=" + encodeURIComponent(content)
    });
    return response.text();
  }
  
  const shareCode = (value) => {
    setModalIsOpen(true)
    setIsLoading(true)
    fetchSharedCodeLink(value).then(url => {setIsLoading(false);setshareURL(url) });
  }

  const handleCodeRun = () => {
    props.executeCode(langId[props.currLang], props.code, props.codeInput);
  };

  const handleCodeDownload = () => {
    // download code here...
    const element = document.createElement("a");
    const file = new Blob([props.code], {
      type: "text/plain;charset=utf-8",
    });
    element.href = URL.createObjectURL(file);
    element.download = `syntaxmeets-code.${getExtensionByLangCode(
      props.currLang
    )}`;
    document.body.appendChild(element);
    element.click();
  };

  const IONavbar = (props) => {
    return (
      <AppBar position="static" style={{ backgroundColor: "#000A29" }}>
        <Typography
          variant="h6"
          style={{
            fontFamily: "poppins",
            color: "white",
            marginRight: "auto",
            marginTop: "auto",
            marginBottom: "auto",
            marginLeft: "auto",
            fontWeight: "400",
            padding: "3px 2px",
          }}
        >
          {props.type}
        </Typography>
      </AppBar>
    );
  };

  const uploadFile = () => {
    document.querySelector("#upload").click();
  };

  const checkValidFileExtension = (file) => {
    const validExtensions = Object.keys(langExtensionDict);
    var name = file.name;
    var valid = false;
    if (name.length > 0) {
      for (var i = 0; i < validExtensions.length; ++i) {
        var ext = validExtensions[i];
        if (
          name.substr(name.length - ext.length, ext.length).toLowerCase() ==
          ext.toLowerCase()
        ) {
          valid = true;
          break;
        }
      }
    }
    return valid;
  };

  const handleFileChange = () => {
    var file = document.querySelector("#upload").files[0];

    if (file) {
      var reader = new FileReader();

      reader.onload = function (e) {
        if (file.size > 10000) {
          setFilePopup(true);
          setFileHandleError("Error: File size greater than 10KB!");
          return;
        }

        if (!checkValidFileExtension(file)) {
          setFilePopup(true);
          setFileHandleError("Error: Not a Valid File Extension!");
          return;
        }

        handleChange(e.target.result);
        const fileNameArr = file.name.split(".");
        const ext = `.${fileNameArr[fileNameArr.length - 1]}`;
        props.setLanguage(langExtensionDict[ext]);
      };

      reader.onerror = function (e) {
        console.error("An error ocurred reading the file", e);
      };

      reader.readAsText(file, "UTF-8");
    }
  };

  // handle fullscreen mode
  const handleFullscreen = (props) =>{
    fullscreen ? setFullscreen(false) : setFullscreen(true);
    props.toggleFocusMode();
  }

  return (
    <Fragment>
      <Dialog fullWidth={true} maxWidth={"sm"} open={props.isCompiling}>
        <DialogTitle style={{ align: "center" }}>Compiling ...</DialogTitle>
        <div className={localClasses.loader}>
          <div>
            <span style={{ paddingLeft: "190px" }}>
              <ShareIcon style={{ fontSize: "125px" }} />
            </span>
            <span className={localClasses.arrow}>&gt;</span>
          </div>
        </div>
      </Dialog>
      <Dialog maxWidth={"sm"} open={props.isError}>
        <DialogTitle>Oops Error Occured</DialogTitle>
        <span style={{ marginLeft: "15px" }}>{props.codeError}</span>
        <DialogActions>
          <Button
            onClick={() => props.setIsError(false)}
            variant="contained"
            size="large"
            color="primary"
          >
            Close
          </Button>
        </DialogActions>
      </Dialog>
      <Snackbar
        open={popup[0]}
        autoHideDuration={2000}
        onClose={() => {
          setPopup([false, ""]);
        }}
      >
        <Alert
          onClose={() => {
            setPopup([false, ""]);
          }}
          severity="success"
          variant="filled"
        >
          {popup[1]}
        </Alert>
      </Snackbar>
      <Snackbar
        open={filePopup}
        autoHideDuration={2000}
        onClose={() => {
          setFilePopup(false);
        }}
      >
        <Alert
          onClose={() => {
            setFilePopup(false);
          }}
          severity="error"
          variant="filled"
        >
          {fileHandleError}
        </Alert>
      </Snackbar>
      <AppBar position="static" style={{ backgroundColor: "#000A29" }}>
        <div className={`${localClasses.Editor__navbar} row`}>
          <Typography
            variant="h5"
            style={{
              fontFamily: "poppins",
              color: "white",
              marginRight: "auto",
              marginTop: "auto",
              marginBottom: "auto",
              marginLeft: "30px",
              fontWeight: "800",
            }}
          >
            &nbsp;Syntax<span style={{ color: "#FFD500" }}>Editor</span>
          </Typography>
          <Toolbar>
            <FormControl
              size="small"
              variant="outlined"
              className={classes.formControl}
            >
              <InputLabel
                id="mode-label"
                style={{ fontFamily: "poppins", color: "#FFD500" }}
              >
                Language
              </InputLabel>
              <Select
                name="mode"
                labelId="mode-label"
                id="select-mode"
                value={props.currLang}
                onChange={(e) => {
                  props.setLanguage(e.target.value);
                }}
                label="Language"
                style={{ fontFamily: "poppins", color: "#ffffff" }}
              >
                {LangOptions.map((language) => (
                  <MenuItem value={language} key={language}>
                    <span className={localClasses.Menu__options}>
                      {language}
                    </span>
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControl
              size="small"
              variant="outlined"
              className={classes.formControl}
            >
              <InputLabel
                id="theme-label"
                style={{ fontFamily: "poppins", color: "#FFD500" }}
              >
                Theme
              </InputLabel>
              <Select
                name="Theme"
                labelId="theme-label"
                id="select-theme"
                onChange={(e) => setTheme(e.target.value)}
                value={theme}
                label="Theme"
                style={{ fontFamily: "poppins", color: "#ffffff" }}
              >
                {themes.map((lang) => (
                  <MenuItem key={lang} value={lang}>
                    <span className={localClasses.Menu__options}> {lang} </span>
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControl
              size="small"
              variant="outlined"
              className={classes.formControl}
            >
              <InputLabel
                id="font-label"
                style={{ fontFamily: "poppins", color: "#FFD500" }}
              >
                Font Size
              </InputLabel>
              <Select
                name="Theme"
                labelId="font-label"
                id="select-font"
                onChange={(e) => props.setFontSize(e.target.value)}
                value={props.fontSize}
                label="Font Size"
                style={{ fontFamily: "poppins", color: "#ffffff" }}
              >
                {[10, 12, 14, 16, 18, 20, 24, 28, 32, 40].map((size) => (
                  <MenuItem key={size} value={size}>
                    <span className={localClasses.Menu__options}> {size} </span>
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Toolbar>
        </div>
      </AppBar>
      <Dialog fullWidth={true} maxWidth={"xs"} open={modalIsOpen}>
        <CloseIcon style={{fontSize: "2em", position: "absolute", right: "5px", top: "5px"}} onClick={()=>{
          setModalIsOpen(false)
          setshareURL("")
        }}/>
        <DialogTitle style={{ textAlign: "center", marginTop: "10px" }}>
          Share Your Code
        </DialogTitle>
        <DialogContent>
        <div style={{display: "flex", alignItems: "center", margin: "20px"}}>
        {isLoading ? 
        <BeatLoader color='red' loading={true} css={override} size={50} /> :
          <>
            <Typography style={{ padding: "5px 10px", background: "#eee", borderRadius: "3px" }}>{shareURL}</Typography>
            <Tooltip title="Copy Url" arrow TransitionComponent={Zoom}>
              <Button
                variant="contained"
                color="primary"
                onClick={() => {
                  copy(shareURL)
                  setPopup([true, "Url Copied !!!"])
                }}
                style={{
                  fontFamily: "poppins",
                  marginLeft: "auto",
                  fontWeight: "600",
                  color: "white",
                }}
                >
                <FileCopyIcon />
              </Button>
            </Tooltip>
          </>
        }
        </div>
        </DialogContent>
      </Dialog>
      <AceEditor
        mode={langMode[props.currLang]}
        theme={theme}
        height="550px"
        width={"auto"}
        value={props.code}
        onChange={handleChange}
        fontSize={props.fontSize}
        showPrintMargin
        showGutter
        highlightActiveLine
        name="CODEEDITOR"
        setOptions={{
          useWorker: false,
          enableLiveAutocompletion: props.autoCompletion,
        }}
      />
      <AppBar
        position="static"
        style={{ backgroundColor: "#000A29", marginBottom: "10px" }}
      >
        <Toolbar>
          <FormControlLabel
            control={
              <Switch
                color="primary"
                checked={props.autoCompletion}
                onChange={() => {
                  props.setAutoCompletion(!props.autoCompletion);
                }}
                name="EnableAutoCompletion"
              />
            }
            label={
              <Typography>
                <span style={{ color: "white" }}>Auto-complete</span>
              </Typography>
            }
          />
          <input
            type="file"
            id="upload"
            onChange={() => handleFileChange()}
            hidden
            accept=".c, .cpp, .java, .js, .ts, .clj, .cljs, .cs, .cbl, .cob, .cpy, .erl, .hrl, .go, .py, .f90, .f95, .f03, .txt, .groovy, .gvy, .gy, .gsh, 	.kt, .kts, .ktm, .php, .r, .rb, .sql, .swift"
          />
          <ButtonGroup
            style={{ marginLeft: "auto" }}
            variant="contained"
            color="primary"
          >
            <Tooltip title="Upload Code" arrow TransitionComponent={Zoom}>
              <Button
                variant="contained"
                color="primary"
                onClick={() => uploadFile()}
                style={{
                  fontFamily: "poppins",
                  marginLeft: "auto",
                  fontWeight: "600",
                  color: "white",
                }}
                >
                <CloudUploadIcon />
              </Button>
            </Tooltip>
            <Tooltip title="Share Code" arrow TransitionComponent={Zoom}>
              <Button
                variant="contained"
                color="primary"
                onClick={() => shareCode(props.code)}
                style={{
                  fontFamily: "poppins",
                  marginLeft: "auto",
                  fontWeight: "600",
                  color: "white",
                }}
                >
                <ShareIcon />
              </Button>
            </Tooltip>
            <Tooltip title="Copy Code" arrow TransitionComponent={Zoom}>
              <Button
                variant="contained"
                color="primary"
                onClick={() => copyCode(props.code)}
                style={{
                  fontFamily: "poppins",
                  marginLeft: "auto",
                  fontWeight: "600",
                  color: "white",
                }}
                >
                <FileCopyIcon />
              </Button>
            </Tooltip>
            <Tooltip title="Download Code" arrow TransitionComponent={Zoom}>
              <Button
                variant="contained"
                color="primary"
                style={{
                  fontFamily: "poppins",
                  marginLeft: "auto",
                  fontWeight: "600",
                  color: "white",
                }}
                onClick={handleCodeDownload}
                >
                <CloudDownloadRounded style={{ fontSize: 24 }} />
              </Button>
            </Tooltip>
            <Tooltip title={fullscreen ? "Exit Full Screen" : "Full Screen"} arrow TransitionComponent={Zoom}>
              <Button
                variant="contained"
                color="primary"
                style={{
                  fontFamily: "poppins",
                  marginLeft: "auto",
                  fontWeight: "600",
                  color: "white",
                }}
                onClick={() => handleFullscreen(props)}
              >
                {fullscreen
                  ?<FullscreenExitRounded style={{ fontSize: 24 }}/>
                  :<FullscreenRounded style={{ fontSize: 24 }}/>
                }
              </Button>
            </Tooltip>
          </ButtonGroup>
          <Button
            variant="contained"
            color="primary"
            onClick={handleCodeRun}
            startIcon={<PlayArrowIcon style={{ fontSize: 24 }} />}
            style={{
              fontFamily: "poppins",
              marginLeft: "10px",
              fontWeight: "600",
              color: "#fff",
              backgroundColor: "#FFD500",
            }}
          >
            Run
          </Button>
        </Toolbar>
      </AppBar>

      <Grid container spacing={0}>
        <Grid item xs={12} sm={12} md={6}>
          <IONavbar type={"Input"} />
          <INPUT />
        </Grid>
        <Grid item xs={12} sm={12} md={6}>
          <IONavbar type={"Output"} />
          <OUTPUT />
        </Grid>
      </Grid>
    </Fragment>
  );
}
Example #22
Source File: Nav.js    From Google-Photos-Clone with MIT License 4 votes vote down vote up
function Nav() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const fileRef = useRef();
  const [uploadMessage, setUploadMessage] = useState(null);
  const user = useSelector((state) => state.user);
  const currentAlbum = useSelector((state) => state.currentAlbum);

  const logout = () => {
    signOut(auth)
      .then(() => dispatch(setUser(null)))
      .catch((err) => console.log(err.message));
  };

  const getUploadImages = () => {
    fileRef.current.click();
  };

  const handleUploadImage = () => {
    const photos = fileRef.current.files;
    if (photos.length === 0) return;

    for (let photo of photos) {
      if (!photo.type.startsWith("image")) {
        return alert("only image can be uploaded");
      }
    }

    if (photos.length > 3) return alert("only 3 images can be uploaded");

    setUploadMessage(`Uploading ${photos.length} Photo`);
    uploadPhoto(photos, currentAlbum, user.uid, setUploadMessage);
  };

  const goToHomePage = () => navigate(`/`);

  return (
    <div className="nav">
      <div className="nav__logo" onClick={goToHomePage}>
        <Typography variant="h5">
          <span style={{ color: "#4285F4" }}>G</span>
          <span style={{ color: "#DB4437" }}>o</span>
          <span style={{ color: "#F4B400" }}>o</span>
          <span style={{ color: "#4285F4" }}>g</span>
          <span style={{ color: "#0F9D58" }}>l</span>
          <span style={{ color: "#DB4437" }}>e</span>
          &nbsp;
          <span className="nav__logoText2">Photos</span>
        </Typography>
      </div>

      <div className="nav_search">
        <SearchIcon className="nav__searchIcon" />
        <input
          type="text"
          className="nav__searchInput"
          placeholder="Search your photos"
        />
      </div>

      <div className="nav__right">
        <Button
          startIcon={<PublishIcon />}
          size="small"
          className="nav__rightUploadBtn"
          onClick={getUploadImages}
        >
          Upload
        </Button>

        <Tooltip title="Logout" arrow>
          <IconButton onClick={logout}>
            <Avatar className="nav__rightAvatar" src={user.photoURL}>
              {user.displayName[0]}
            </Avatar>
          </IconButton>
        </Tooltip>
      </div>

      <input
        type="file"
        onChange={handleUploadImage}
        ref={fileRef}
        multiple
        accept="image/*"
        style={{ display: "none" }}
      />

      {uploadMessage && (
        <Snackbar
          onClose={() => setUploadMessage(null)}
          autoHideDuration={3000}
          open={Boolean(uploadMessage)}
          anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
          message={uploadMessage}
        />
      )}
    </div>
  );
}
Example #23
Source File: LTI.js    From eSim-Cloud with GNU General Public License v3.0 4 votes vote down vote up
export default function LTIConfig () {
  const classes = useStyles()

  const [ltiDetails, setLTIDetails] = React.useState({
    secretKey: '',
    consumerKey: '',
    configURL: '',
    configExists: false,
    consumerError: '',
    score: '',
    initialSchematic: '',
    modelSchematic: '',
    testCase: null,
    scored: true,
    id: ''
  })

  const { secretKey, consumerKey, configURL, configExists, score, modelSchematic } = ltiDetails
  const [schematic, setSchematic] = React.useState('')
  const [history, setHistory] = React.useState([])
  const [historyId, setHistoryId] = React.useState('')
  const [schematics, setSchematics] = React.useState([])
  const [update, setUpdate] = React.useState(false)
  const [submitMessage, setSubmitMessage] = React.useState('')
  const [activeSim, setActiveSim] = React.useState(null)
  const [simParam, setSimParam] = React.useState([])

  useEffect(() => {
    console.log(activeSim)
  }, [activeSim])

  useEffect(() => {
    var url = queryString.parse(window.location.href.split('lti?')[1])
    const token = localStorage.getItem('esim_token')
    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    }
    if (token) {
      config.headers.Authorization = `Token ${token}`
    }
    api.get(`save/versions/${url.id}`, config).then(res => {
      res.data.map(ele => {
        ele.save_time = new Date(ele.save_time)
        return 0
      })
      setSchematics(res.data)
    }).catch(err => {
      console.log(err)
    })
    // eslint-disable-next-line
  }, [])

  useEffect(() => {
    var url = queryString.parse(window.location.href.split('lti?')[1])
    const token = localStorage.getItem('esim_token')
    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    }
    if (token) {
      config.headers.Authorization = `Token ${token}`
    }
    api.get(`lti/exist/${url.id}`, config).then(res => {
      setLTIDetails(
        {
          modelSchematic: res.data.model_schematic,
          secretKey: res.data.secret_key,
          consumerKey: res.data.consumer_key,
          configURL: res.data.config_url,
          score: res.data.score,
          configExists: true,
          initialSchematic: res.data.model_schematic,
          testCase: res.data.test_case,
          scored: res.data.scored,
          id: res.data.id
        })
      setSchematic(`${res.data.model_schematic.version}-${res.data.model_schematic.branch}`)
      if (res.data.test_case === null) {
        setHistoryId('None')
      } else {
        setHistoryId(res.data.test_case)
      }
    }).catch(err => {
      console.log(err)
      api.get(`save/${url.id}/${url.version}/${url.branch}`, config).then(res => {
        setLTIDetails(
          {
            modelSchematic: res.data,
            scored: true
          })
        setSchematic(`${res.data.version}-${res.data.branch}`)
      })
    })
  }, [])

  useEffect(() => {
    var url = queryString.parse(window.location.href.split('lti?')[1])
    const token = localStorage.getItem('esim_token')
    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    }
    if (token) {
      config.headers.Authorization = `Token ${token}`
    }
    api.get(`simulation/history/${url.id}/${schematic.split('-')[0]}/${schematic.split('-')[1]}/${null}`, config).then(res => {
      res.data.map(ele => {
        ele.simulation_time = new Date(ele.simulation_time)
        return 0
      })
      setHistory(res.data)
    }).catch(err => {
      console.log(err)
    })
  }, [schematic])

  // eslint-disable-next-line
  const handleLTIGenerate = () => {
    var score = ''
    if (!ltiDetails.scored) {
      score = null
    } else {
      score = ltiDetails.score
    }
    const body = {
      consumer_key: ltiDetails.consumerKey,
      secret_key: ltiDetails.secretKey,
      model_schematic: ltiDetails.modelSchematic.id,
      score: score,
      initial_schematic: ltiDetails.modelSchematic.id,
      test_case: ltiDetails.testCase,
      scored: ltiDetails.scored
    }
    console.log(body)
    api.post('lti/build/', body)
      .then(res => {
        setLTIDetails({
          ...ltiDetails,
          configURL: res.data.config_url,
          configExists: true,
          consumerError: '',
          score: res.data.score,
          id: res.data.id
        })
        return res.data
      })
      .catch((err) => {
        console.log(err.data)
        setLTIDetails({ ...ltiDetails, consumerError: 'An error was encountered while setting the details!' })
      })
  }

  const handleUpdateClose = () => {
    setUpdate(false)
  }

  const handleDeleteLTIApp = () => {
    api.delete(`lti/delete/${ltiDetails.modelSchematic.id}`)
      .then(res => {
        setLTIDetails({
          secretKey: '',
          consumerKey: '',
          configURL: '',
          configExists: false,
          consumerError: '',
          score: '',
          initialSchematic: '',
          modelSchematic: modelSchematic,
          testCase: null,
          id: ''
        })
        setHistoryId('')
      })
      .catch(error => console.log(error))
  }

  const handleConsumerKey = (e) => {
    setLTIDetails({ ...ltiDetails, consumerKey: e.target.value })
  }

  const handleSecretKey = (e) => {
    setLTIDetails({ ...ltiDetails, secretKey: e.target.value })
  }

  const handleScore = (e) => {
    if (e.target.value > 1 || e.target.value < 0) {
      // To-DO: Show error message
    } else {
      setLTIDetails({ ...ltiDetails, score: e.target.value })
    }
  }

  const handleCheckChange = (e) => {
    setLTIDetails({ ...ltiDetails, scored: e.target.checked })
  }

  const handleChange = (e) => {
    var schematic = null
    schematics.forEach(element => {
      if (element.version === e.target.value.split('-')[0] && element.branch === e.target.value.split('-')[1]) {
        schematic = element
      }
    })
    setSchematic(e.target.value)
    setLTIDetails({ ...ltiDetails, modelSchematic: schematic })
  }

  const handleChangeSim = (e) => {
    if (e.target.value === 'None') {
      setLTIDetails({ ...ltiDetails, testCase: null })
    } else {
      setLTIDetails({ ...ltiDetails, testCase: e.target.value })
      var temp = history.find(ele => ele.id === e.target.value)
      setActiveSim(temp)
    }
    setHistoryId(e.target.value)
  }

  const handleSimParamChange = (event) => {
    setSimParam(event.target.value)
  }

  const handleOnClick = () => {
    var score = ''
    if (!ltiDetails.scored) {
      score = null
    } else {
      score = ltiDetails.score
    }
    const body = {
      consumer_key: ltiDetails.consumerKey,
      secret_key: ltiDetails.secretKey,
      model_schematic: ltiDetails.modelSchematic.id,
      score: score,
      initial_schematic: ltiDetails.modelSchematic.id,
      test_case: ltiDetails.testCase,
      scored: ltiDetails.scored,
      id: ltiDetails.id
    }
    console.log(body)
    api.post('lti/update/', body)
      .then(res => {
        setLTIDetails({
          ...ltiDetails,
          configURL: res.data.config_url,
          configExists: true,
          consumerError: '',
          score: res.data.score
        })
        setUpdate(true)
        setSubmitMessage('Updated Successfully')
        return res.data
      })
      .catch((err) => {
        console.log(err.data)
        setSubmitMessage('An error was encountered!')
      })
  }

  const handleUrlCopy = () => {
    var copyText = document.querySelector('.lti-url')
    console.log(copyText)
    copyText.select()
    copyText.setSelectionRange(0, 99999)
    document.execCommand('copy')
  }

  return (
    <>
      {ltiDetails && <>
        <div style={{ display: 'flex' }}>
          <Card className={classes.root} style={{ marginLeft: '2%' }}>
            <CardActionArea>
              <CardMedia
                className={classes.media}
                image={ltiDetails.modelSchematic.base64_image}
                title="Schematic"
              />
              <CardContent>
                <Typography gutterBottom variant="h5" component="h2">
                  Schematic
                </Typography>
              </CardContent>
            </CardActionArea>
          </Card>
          {/* {ltiDetails.initialSchematic && <Card className={classes.root} style={{ marginLeft: '2%' }}>
            <CardActionArea>
              <CardMedia
                className={classes.media}
                image={initial.base64_image}
                title="Initial Schematic"
              />
              <CardContent>
                <Typography gutterBottom variant="h5" component="h2">
                  Initial Schematic
                </Typography>
              </CardContent>
            </CardActionArea>
          </Card>} */}
          <div style={{ minWidth: '500px', marginLeft: '2%', marginTop: '2%' }}>
            {ltiDetails.consumerError && <h3>{ltiDetails.consumerError}</h3>}
            <TextField id="standard-basic" label="Consumer Key" defaultValue={consumerKey} onChange={handleConsumerKey} value={consumerKey} />
            <TextField style={{ marginLeft: '1%' }} id="standard-basic" label="Secret Key" defaultValue={secretKey} onChange={handleSecretKey} value={secretKey} />
            <TextField style={{ marginLeft: '1%' }} id="standard-basic" label="Score" defaultValue={score} onChange={handleScore} value={score} disabled={!ltiDetails.scored} />
            <FormControl style={{ marginTop: '1%' }} className={classes.formControl}>
              <InputLabel htmlFor="outlined-age-native-simple">Schematic</InputLabel>
              <Select
                labelId="demo-simple-select-placeholder-label-label"
                id="demo-simple-select-placeholder-label"
                value={schematic}
                style={{ minWidth: '300px' }}
                onChange={handleChange}
                label="Schematic"
                className={classes.selectEmpty}
              >
                {schematics.map(schematic => {
                  return <MenuItem key={schematic.version} value={`${schematic.version}-${schematic.branch}`}>{schematic.name} of variation {schematic.branch} saved at {schematic.save_time.toLocaleString()}</MenuItem>
                })}
              </Select>
            </FormControl>
            <FormControl style={{ marginLeft: '2%', marginTop: '1%' }} className={classes.formControl}>
              <InputLabel htmlFor="outlined-age-native-simple">Test Case</InputLabel>
              {history && <Select
                labelId="select-simulation-history"
                id="select-sim"
                value={historyId}
                style={{ minWidth: '300px' }}
                onChange={handleChangeSim}
                label="Test Case"
                className={classes.selectEmpty}
                inputProps={{ readOnly: !ltiDetails.scored }}
              >
                <MenuItem value="None">
                  None
                </MenuItem>
                {history.map(sim => {
                  return <MenuItem key={sim.id} value={sim.id}>{sim.simulation_type} at {sim.simulation_time.toLocaleString()}</MenuItem>
                })}
              </Select>}
            </FormControl>
            <br />
            {activeSim && <FormControl style={{ marginTop: '1%', minWidth: 200 }} className={classes.formControl}>
              <InputLabel id="demo-mutiple-chip-label">Comparison Parameter</InputLabel>
              {history && <Select
                labelId="select-comparison-parameter"
                id="demo-mutiple-chip"
                multiple
                value={simParam}
                onChange={handleSimParamChange}
                input={<Input id="select-multiple-chip" />}
                inputProps={{ readOnly: !ltiDetails.scored }}
                renderValue={(selected) => (
                  <div className={classes.chips}>
                    {selected.map((value) => (
                      <Chip key={value} label={value} className={classes.chip} />
                    ))}
                  </div>
                )}
              >
                {activeSim.result.data.map(params => {
                  return <MenuItem key={params[0]} value={params[0]}>{params[0]}</MenuItem>
                })}
              </Select>}
            </FormControl>}
            <FormControlLabel
              style={{ marginLeft: '1%', marginTop: '2%' }}
              control={
                <Checkbox
                  checked={ltiDetails.scored}
                  onChange={handleCheckChange}
                  name="scored"
                  color="primary"
                />
              }
              label="Scored?"
            />
          </div>
        </div>
        <div>
          <Button style={{ marginTop: '1%', marginLeft: '2%', minWidth: 300 }} disableElevation variant="contained" color="primary" href='/eda/#/dashboard' startIcon={<ArrowBackIcon />}>
            Return to Dashboard
          </Button>
          <Button style={{ marginTop: '1%', marginLeft: '1%', minWidth: 300 }} disableElevation variant="contained" color="primary" disabled={configExists} onClick={handleLTIGenerate}>
            Create LTI URL
          </Button>
          {configExists &&
            <Button
              style={{ marginLeft: '1%', marginTop: '1%', minWidth: 300 }}
              disableElevation
              color="primary"
              variant="contained"
              href={`#/submission?consumer_key=${ltiDetails.consumerKey}`}
            >
              Submissions
            </Button>}
          {configExists && <Button
            style={{ marginLeft: '1%', marginTop: '1%', minWidth: 297 }}
            disableElevation
            color="primary"
            variant="contained"
            onClick={handleOnClick} >
            Update LTI App
          </Button>}
          {configExists &&
            <Button
              style={{ marginLeft: '1%', marginTop: '1%', minWidth: 300 }}
              disableElevation
              variant="contained"
              className={classes.delete}
              startIcon={<DeleteIcon />}
              onClick={() => handleDeleteLTIApp()}
            >
              Delete
            </Button>}
          {configURL && <div style={{ display: 'flex', marginTop: '1%', marginLeft: '2%' }}>
            <h3 className={classes.config} style={{ float: 'left', marginTop: '1.1%' }}>URL for LTI Access:</h3>
            <h3 className={classes.config} style={{ float: 'left' }}>
              <TextareaAutosize className="lti-url" value={configURL} maxRows={1} style={{ fontSize: '18px', width: 1200, maxWidth: 1200, border: 'none' }} />
            </h3>
            <Button style={{ float: 'right', height: '50%', marginTop: '0.7%', marginLeft: '1%', minWidth: 200 }} disableElevation variant="contained" color="primary" onClick={handleUrlCopy}>
              Copy LTI URL
            </Button>

          </div>}
        </div>
        <Snackbar
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'left'
          }}
          open={update}
          autoHideDuration={2000}
          onClose={handleUpdateClose}
          message={submitMessage}
          action={
            <>
              <IconButton size="small" aria-label="close" color="inherit" onClick={handleUpdateClose}>
                <CloseIcon fontSize="small" />
              </IconButton>
            </>
          }
        />
      </>}
    </>
  )
}
Example #24
Source File: SignUp.jsx    From pwa with MIT License 4 votes vote down vote up
export default function SignUp({ onBackClick, onSMSSent }) {
  const [phone, setPhone] = useState('');
  const [condition, setCondition] = useState('');

  const [isDialogOpen, setIsDialogOpen] = useState(false);

  const [isAlertOpen, setIsAlertOpen] = useState(false);
  const [alertText, setAlertText] = useState('');

  function onSubmit() {
    if (!/09\d{9}/.test(perToEngDigits(phone))) {
      setAlertText('شماره همراه وارد شده صحیح نمی‌باشد.');
      setIsAlertOpen(true);
      return;
    }
    if (condition === '') {
      setAlertText('وضعیت شرایط خاص را مشخص کنید.');
      setIsAlertOpen(true);
      return;
    }
    sendActivationSMS();
  }

  function sendActivationSMS() {
    setIsDialogOpen(true);
    axios({
      method: 'POST',
      url: `${process.env.REACT_APP_REGISTER_USER}`,
      data: {
        phone_number: perToEngDigits(phone),
        risk_group: condition,
      },
    })
      .then(({ data }) => {
        setIsDialogOpen(false);
        onSMSSent({
          phone: perToEngDigits(phone),
          condition,
          ttl: data.activate_ttl,
        });
      })
      .catch((err) => {
        console.error(err);
        setIsDialogOpen(false);
        setAlertText('ارسال کد با خطا مواجه شد!');
        setIsAlertOpen(true);
      });
  }

  return (
    <>
      <AppBar position="static" className="activity-header">
        <Toolbar>
          <img src={logo} className="app-header-logo" alt="logo" />
          <IconButton color="inherit" onClick={onBackClick}>
            <KeyboardBackspace />
          </IconButton>
        </Toolbar>
      </AppBar>
      <div className={styles.container}>
        <TextField
          label="شماره همراه"
          value={phone}
          onChange={(e) => setPhone(e.target.value)}
          fullWidth
        />
        <Box mt={2}>
          <FormControl fullWidth>
            <InputLabel id="condition-select-label">
              شرایط خاص دارید؟
            </InputLabel>
            <Select
              id="condition-select"
              labelId="condition-select-label"
              value={condition}
              onChange={(e) => setCondition(e.target.value)}
            >
              <MenuItem value={0}>
                <div className={styles.menuItem}>
                  <strong>۱. بدون شرایط خاص</strong>
                </div>
              </MenuItem>
              <MenuItem
                value={1}
                style={{ whiteSpace: 'normal', textAlign: 'justify' }}
              >
                <div className={styles.menuItem}>
                  <strong>۲. بیماران با نقص ایمنی:</strong>
                  &nbsp; تحت درمان با کورتیکواستروئید، شیمی درمانی، بدخیمی‌ها،
                  پیوند اعضا، مبتلایان به HIV
                </div>
              </MenuItem>
              <MenuItem
                value={2}
                style={{ whiteSpace: 'normal', textAlign: 'justify' }}
              >
                <div className={styles.menuItem}>
                  <strong>۳. بیماران با بیماری زمینه‌ای و سالمندان:</strong>
                  &nbsp; بیماری قلبی عروقی، فشار خون، بیماری‌های تنفسی زمینه‌ای،
                  دیابت و افراد بالای ۵۰ سال
                </div>
              </MenuItem>
            </Select>
          </FormControl>
        </Box>
        <Box mt={2}>
          <Typography variant="subtitle2" align="center">
            برای استفاده از قابلیت پیگیری وضعیت سلامتی لازم است ابتدا در
            نرم‌افزار ثبت‌نام کنید.
          </Typography>
        </Box>
        <Box mt={2} className={styles.verificationButtonContainer}>
          <Button
            variant="contained"
            color="primary"
            size="large"
            onClick={onSubmit}
            className={styles.verificationButton}
          >
            ارسال کد فعال‌سازی
          </Button>
        </Box>
      </div>
      <Dialog open={isDialogOpen}>
        <div className={styles.dialogContent}>
          <CircularProgress />
          <Box ml={3}>{'لطفا کمی صبر کنید.'}</Box>
        </div>
      </Dialog>
      <Snackbar
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'center',
        }}
        open={isAlertOpen}
        autoHideDuration={5000}
        onClose={() => setIsAlertOpen(false)}
        message={alertText}
      />
    </>
  );
}
Example #25
Source File: Admin.js    From FireShort with MIT License 4 votes vote down vote up
render() {
    const { classes } = this.props;
    const { inputBackdrop, newPsw } = this.state;

    return (
      <React.Fragment>
        {inputBackdrop ? (
          <div
            style={{
              position: 'fixed',
              width: '100vw',
              height: '100vh',
              background: 'rgb(0,0,0,.5)',
              display: 'grid',
              placeItems: 'center',
              zIndex: 10,
            }}
          >
            <div style={{ padding: "20px", backgroundColor: "white" }}>
              <h3>Protect Link With Password</h3>
              <div style={{ display: "block", padding: "20px" }}>
                <input
                  placeholder='Enter Password...'
                  value={newPsw}
                  style={{ padding: "15px", fontSize: "15px", borderRadius: "2px", width: "100%" }}
                  onChange={(e) => this.setState({ newPsw: e.target.value })}
                />
                <div style={{ marginTop: "25px" }}>
                  <button onClick={(e) => this.onPswSave(e)} style={{ padding: "12px", color: "white", backgroundColor: "black", fontSize: "15px", border: "none", marginRight: "15px", borderRadius: "5px", cursor: "pointer" }}>Save</button>
                  <button onClick={(e) => this.setState({ inputBackdrop: false })} style={{ padding: "12px", color: "white", backgroundColor: "red", fontSize: "15px", border: "none", marginRight: "15px", borderRadius: "5px", cursor: "pointer" }}>Cancel</button>
                </div>
              </div>
            </div>
          </div>
        ) : null}
        <CssBaseline />
        <Header />
        {this.state.loading && <LinearProgress color='secondary' />}
        <main>
          <MainToolBar
            state={this.state}
            updateViewMode={this.updateViewMode}
            refresh={this.updateUrls}
          />
          {this.state.shortUrls.length > 0 ? (
            <>
              {this.state.viewMode === 'module' ? (
                <CardUrls
                  shortUrls={this.props.links}
                  handleEditShortUrl={this.handleEditShortUrl}
                  handleDeleteShortUrl={this.handleDeleteShortUrl}
                  openHits={this.getHits}
                // updateHits={this.updateUrls}
                  toggleSecurity={this.toggleSecurity}
                />
              ) : (
                  <ListUrls
                    shortUrls={this.state.shortUrls}
                    handleEditShortUrl={this.handleEditShortUrl}
                    handleDeleteShortUrl={this.handleDeleteShortUrl}
                    toggleSecurity={this.toggleSecurity}
                    openHits={this.getHits}
                  />
                )}
            </>
          ) : (  
              <>                            
                  {this.state.loading == false &&                      
                    <Container maxWidth='md'>
                      <img src={'/Images/pixeltrue-search.svg'} style={{margin: "30px auto", display: "block", width: "100%", maxHeight: "400px" }} />
                      <Card className={classes.toolBarRoot} style={{marginBottom: "30px"}}>
                        <Typography align="center" style={{padding: "30px 60px"}} variant="h6">
                          Oops! Looks like you don't have any links. Press the "+" icon below to start adding links.
                        </Typography>   
                      </Card>                                
                    </Container>              
                  }
              </>                                
            )}

          <Fab
            aria-label='Add'
            className={classes.fab}
            color='primary'
            onClick={this.handleClickOpen}
          >
            <AddIcon />
          </Fab>

          <Backdrop className={classes.backdrop} open={this.state.backdrop}>
            <CircularProgress color='inherit' />
          </Backdrop>

          <UrlsDialog
            state={this.state}
            handleClose={this.handleClose}
            handleLurlChange={this.handleLurlChange}
            handleCurlChange={this.handleCurlChange}
            handleSubmit={this.handleSubmit}
            handleTrackChange={this.handleTrackChange}
            handleProtectChange={this.handleProtectChange}
            handlePswChange={this.handlePswChange}
          />

          <HitsDialog
            state={this.state}
            hitActivity={this.state.hits}
            handleClose={this.handleClose}
          />

          <Snackbar
            open={this.state.successToast}
            autoHideDuration={6000}
            onClose={this.handleToastClose}
          >
            <Alert onClose={this.handleToastClose} severity='success'>
              Successfully added!
            </Alert>
          </Snackbar>
        </main>
      </React.Fragment>
    );
  }
Example #26
Source File: uuid-sdk.js    From js-miniapp with MIT License 4 votes vote down vote up
UuidFetcher = (props: UUIDProps) => {
  const classes = useStyles();
  const [copyStatus, setCopyStatus] = useState({
    success: false,
    error: false,
  });

  function textCopied(text, result) {
    if (result) {
      setCopyStatus({ success: true, error: false });
    } else {
      setCopyStatus({ success: false, error: true });
    }
  }

  return (
    <GreyCard className={classes.card}>
      <CardContent className={classes.content}>
        {props.messagingUniqueId ??
          props.messagingUniqueIdError ??
          'Not Available'}
      </CardContent>

      <CardActions className={classes.actions}>
        <Button
          data-testid="get-messaging-unique-id"
          variant="contained"
          color="primary"
          fullWidth
          onClick={props.getMessagingUniqueId}
        >
          GET MESSAGING UNIQUE ID
        </Button>
        <CopyToClipboard
          disabled={!props.messagingUniqueId}
          text={props.messagingUniqueId}
          onCopy={textCopied}
        >
          <Button
            disabled={!props.messagingUniqueId}
            data-testid="clipboard-copy"
            variant="contained"
            color="primary"
          >
            Copy
          </Button>
        </CopyToClipboard>
        <Snackbar
          open={copyStatus.success}
          autoHideDuration={3000}
          onClose={() => {
            setCopyStatus({ success: false, error: false });
          }}
          message="Copied to clipboard !!"
        />
        <Snackbar
          open={copyStatus.error}
          autoHideDuration={3000}
          onClose={() => {
            setCopyStatus({ success: false, error: false });
          }}
          message="Failed to copy!"
        />
      </CardActions>

      <CardContent className={classes.content}>
        {props.mauid ?? props.mauidError ?? 'Not Available'}
      </CardContent>

      <CardActions className={classes.actions}>
        <Button
          data-testid="get-mauid"
          variant="contained"
          color="primary"
          fullWidth
          onClick={props.getMauid}
        >
          GET MAUID
        </Button>
        <CopyToClipboard
          disabled={!props.mauid}
          text={props.mauid}
          onCopy={textCopied}
        >
          <Button
            disabled={!props.mauid}
            data-testid="clipboard-copy"
            variant="contained"
            color="primary"
          >
            Copy
          </Button>
        </CopyToClipboard>
      </CardActions>
    </GreyCard>
  );
}
Example #27
Source File: snackbar.jsx    From ileverage-finance with MIT License 4 votes vote down vote up
render() {

    const { type, message, t } = this.props

    let icon = <SuccessIcon color={colors.blue} />
    let color = colors.blue
    let messageType = ''
    let actions = [
      <IconButton
        key="close"
        aria-label="Close"
        onClick={this.handleClose}
      >
        <CloseIcon />
      </IconButton>,
    ]

    switch (type) {
      case 'Error':
        icon = <ErrorIcon color={colors.red} />
        color = colors.red
        messageType = t("Snackbar.Error")
        break;
      case 'Success':
        icon = <SuccessIcon color={colors.blue} />
        color = colors.blue
        messageType = t("Snackbar.Success")
        break;
      case 'Warning':
        icon = <WarningIcon color={colors.orange} />
        color = colors.orange
        messageType = t("Snackbar.Warning")
        break;
      case 'Info':
        icon = <InfoIcon color={colors.blue} />
        color = colors.blue
        messageType = t("Snackbar.Info")
        break;
      case 'Hash':
        icon = <SuccessIcon color={colors.blue} />
        color = colors.blue
        messageType = t("Snackbar.Hash")

        let snackbarMessage = 'https://etherscan.io/tx/'+message;
        actions = [<Button variant="text" size="small" onClick={()=> window.open(snackbarMessage, "_blank")}>
          View
        </Button>,
          <IconButton
            key="close"
            aria-label="Close"
            onClick={this.handleClose}
          >
            <CloseIcon />
          </IconButton>,
        ]
        break;
      default:
        icon = <SuccessIcon color={colors.blue} />
        color = colors.blue
        messageType = t("Snackbar.Success")
        break;
    }

    return (
      <Snackbar
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
        open={this.state.open}
        autoHideDuration={6000}
        onClose={this.handleClose}
        message={
          <div style={{ padding: '12px', borderLeft: '5px solid '+color, borderRadius: '4px'}}>
            {icon}
            <div style={{ display: 'inline-block', verticalAlign: 'middle', maxWidth: '400px' }}>
              <Typography variant='body1' style={{ fontSize: '12px', color: color }}>{ messageType }</Typography>
              <Typography variant='body1' style={{ fontSize: '10px', color: colors.lightBlack }}>{ message }</Typography>
            </div>
          </div>
        }
        action={actions}
      />
    );
  }
Example #28
Source File: snackbar.jsx    From yuni.finance with MIT License 4 votes vote down vote up
render() {

    const { type, message } = this.props

    let icon = <SuccessIcon color={colors.blue} />
    let color = colors.blue
    let messageType = ''
    let actions = [
      <IconButton
        key="close"
        aria-label="Close"
        onClick={this.handleClose}
      >
        <CloseIcon />
      </IconButton>,
    ]

    switch (type) {
      case 'Error':
        icon = <ErrorIcon color={colors.red} />
        color = colors.red
        messageType = 'Error'
        break;
      case 'Success':
        icon = <SuccessIcon color={colors.blue} />
        color = colors.blue
        messageType = 'Success'
        break;
      case 'Warning':
        icon = <WarningIcon color={colors.orange} />
        color = colors.orange
        messageType = 'Warning'
        break;
      case 'Info':
        icon = <InfoIcon color={colors.blue} />
        color = colors.blue
        messageType = 'Info'
        break;
      case 'Hash':
        icon = <SuccessIcon color={colors.blue} />
        color = colors.blue
        messageType = 'Hash'

        let snackbarMessage = 'https://etherscan.io/tx/'+message;
        actions = [<Button variant="text" size="small" onClick={()=> window.open(snackbarMessage, "_blank")}>
          View
        </Button>,
          <IconButton
            key="close"
            aria-label="Close"
            onClick={this.handleClose}
          >
            <CloseIcon />
          </IconButton>,
        ]
        break;
      default:
        icon = <SuccessIcon color={colors.blue} />
        color = colors.blue
        messageType = 'Success'
        break;
    }

    return (
      <Snackbar
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
        open={this.state.open}
        autoHideDuration={6000}
        onClose={this.handleClose}
        message={
          <div style={{ padding: '12px', borderLeft: '5px solid '+color, borderRadius: '4px'}}>
            {icon}
            <div style={{ display: 'inline-block', verticalAlign: 'middle', maxWidth: '400px' }}>
              <Typography variant='body1' style={{ fontSize: '12px', color: color }}>{ messageType }</Typography>
              <Typography variant='body1' style={{ fontSize: '10px', color: colors.lightBlack }}>{ message }</Typography>
            </div>
          </div>
        }
        action={actions}
      />
    );
  }
Example #29
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 "";
		}
	}