@material-ui/core#Modal JavaScript Examples

The following examples show how to use @material-ui/core#Modal. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js    From AED-Map with MIT License 6 votes vote down vote up
ModalWrapper = ({ ButtonOpen, ModalContent }) => {
  const classes = useStyles();
  const [open, setOpen] = useState(false);

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

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

  return (
    <>
      <ButtonOpen handleOpen={handleOpen} />

      <Modal
        className={classes.modal}
        open={open}
        onClose={handleClose}
        closeAfterTransition
        BackdropComponent={Backdrop}
        BackdropProps={{
          timeout: 500
        }}
      >
        <Fade in={open}>
          <div className={classes.paper}>
            <ModalContent handleClose={handleClose} />
          </div>
        </Fade>
      </Modal>
    </>
  );
}
Example #2
Source File: AttemptedModal.js    From quizdom with MIT License 6 votes vote down vote up
AttemptedModal = ({ result, totalScore, showModal }) => {
	const classes = useStyles()
	const [open, setOpen] = useState(showModal)

	useEffect(() => {
		setOpen(showModal)
	}, [showModal])

	return (
		<div className={classes.root}>
			<Modal
				aria-labelledby="transition-modal-title"
				aria-describedby="transition-modal-description"
				className={classes.modal}
				open={open}
				disableEnforceFocus={true}
			>
				<div className={classes.paper}>
					<h2>Quiz Attempted Successfully.</h2>
					<h1 className="score_h2">
						{result.error
							? "Not Submitted ! "
							: `Score: ${result.score}/${totalScore}`}
					</h1>
					<Link to={"/dashboard"}>
						<button className="button wd-200">Dashboard</button>
					</Link>
				</div>
			</Modal>
		</div>
	)
}
Example #3
Source File: Modal.js    From web-wallet with Apache License 2.0 6 votes vote down vote up
function _Modal ({
  children,
  open,
  onClose,
  light
}) {
  const classes = useStyles();

  return (
    <Modal
      aria-labelledby='transition-modal-title'
      aria-describedby='transition-modal-description'
      className={classes.modal}
      open={open}
      onClose={onClose}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={open}>
        <div
          className={[
            classes.paper,
            light ? classes.light : ''
          ].join(' ')}
        >
          {children}
        </div>
      </Fade>
    </Modal>
  );
}
Example #4
Source File: EdlibModal.jsx    From Edlib with GNU General Public License v3.0 6 votes vote down vote up
EdlibModal = ({ onClose, onResourceSelected, contentOnly = false }) => {
    if (contentOnly) {
        return <EdlibModalContent onClose={onClose} />;
    }

    return (
        <Modal
            open={true}
            width="100%"
            onClose={onClose}
            style={{ margin: 20 }}
        >
            <div>
                <EdlibModalContent
                    onClose={onClose}
                    onResourceSelected={onResourceSelected}
                    height="calc(100vh - 40px)"
                />
            </div>
        </Modal>
    );
}
Example #5
Source File: index.js    From Edlib with GNU General Public License v3.0 6 votes vote down vote up
function LoadingModal(props) {
    const {
        open,
        classes,
        contentIcon,
        contentTitle,
        contentText,
    } = props;

    return (
        <Modal
            open={open}
            classes={classes.root}
        >
            <div
                className={classes.paper}
            >
                <Icon className={classes.icon}>sync</Icon>
                <p>{contentText}</p>
                <img src={contentIcon} alt="image" className={classes.image} />
                <span className={classes.title}>
                    {contentTitle}
                </span>
            </div>
        </Modal>
    );
}
Example #6
Source File: CreateBoard.js    From TrelloClone with MIT License 5 votes vote down vote up
CreateBoard = ({ history }) => {
  const classes = useStyles();
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState('');
  const dispatch = useDispatch();

  const onSubmit = async (e) => {
    e.preventDefault();
    dispatch(addBoard({ title }, history));
  };

  const body = (
    <div className={`${classes.paper} ${classes.createBoardModal}`}>
      <div className={classes.modalTop}>
        <h1>Create new board</h1>
        <Button onClick={() => setOpen(false)}>
          <CloseIcon />
        </Button>
      </div>
      <form onSubmit={(e) => onSubmit(e)}>
        <TextField
          variant='outlined'
          margin='normal'
          required
          fullWidth
          label='Add board title'
          autoFocus
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
        <Button type='submit' fullWidth variant='contained' color='primary'>
          Create Board
        </Button>
      </form>
    </div>
  );

  return (
    <div>
      <button className='board-card create-board-card' onClick={() => setOpen(true)}>
        Create new board
      </button>
      <Modal open={open} onClose={() => setOpen(false)}>
        {body}
      </Modal>
    </div>
  );
}
Example #7
Source File: BlackboxView.js    From Nemesis with GNU General Public License v3.0 5 votes vote down vote up
render() {
    let normalizedPercent =
      ((this.state.storageInfo.usedSize - 0) * 100) /
      (this.state.storageInfo.totalSize - 0);
    return (
      <div>
        <Paper>
          <div style={{ position: "relative" }}>
            <Typography variant="caption" className="absolute-center-text">
              {this.state.storageInfo.usedSize}/
              {this.state.storageInfo.totalSize}
            </Typography>
            <Typography variant="caption">
              <FormattedMessage
                id="blackbox.flash-used"
                values={{ percent: normalizedPercent.toFixed(2) }}
              />
            </Typography>
            <LinearProgress
              variant="determinate"
              style={{ height: 20, margin: 10 }}
              value={normalizedPercent}
            />
            <br />
            <Button
              onClick={() => FCConnector.sendCommand(this.props.storageCommand)}
              variant="contained"
              color="primary"
            >
              <FormattedMessage id="blackbox.load-drive" />
            </Button>
            <Button
              onClick={() =>
                FCConnector.storage("erase").then(() => {
                  this.setState({
                    modalOpen: true,
                    modalMessage: "Erase Complete"
                  });
                })
              }
              variant="contained"
              color="secondary"
              style={{ marginLeft: 20 }}
            >
              <FormattedMessage id="blackbox.erase-storage" />
            </Button>
            <Modal open={this.state.modalOpen} onClose={this.handleModalClose}>
              <div className="notification-modal">
                <Typography variant="h6">{this.state.modalMessage}</Typography>
                <Button
                  variant="contained"
                  color="primary"
                  onClick={this.handleModalClose}
                >
                  <FormattedMessage id="common.finished" />
                </Button>
              </div>
            </Modal>
          </div>
        </Paper>
        <Paper>
          <ConfigListView
            fcConfig={this.props.fcConfig}
            notifyDirty={this.props.notifyDirty}
            items={this.props.items}
          />
        </Paper>
      </div>
    );
  }
Example #8
Source File: EditEdlibResourceModal.jsx    From Edlib with GNU General Public License v3.0 5 votes vote down vote up
EditEdlibResourceModal = ({
    removePadding,
    ltiLaunchUrl,
    onClose,
    header,
    onUpdateDone,
}) => {
    return (
        <Modal
            open={true}
            width="100%"
            onClose={onClose}
            style={{ margin: removePadding ? 0 : 20 }}
        >
            <div
                style={{
                    height: removePadding ? '100vh' : 'calc(100vh - 40px)',
                }}
            >
                <EdlibIframe
                    path="/s/edit-from-lti-link"
                    params={{
                        ltiLaunchUrl,
                        resourceTitle: header || 'Title',
                    }}
                    onAction={(data) => {
                        switch (data.messageType) {
                            case 'onClose':
                                onClose();
                                break;
                            case 'onUpdateDone':
                                onUpdateDone(data.extras);
                                break;
                            default:
                                break;
                        }
                    }}
                />
            </div>
        </Modal>
    );
}
Example #9
Source File: index.jsx    From Pandaudio with MIT License 5 votes vote down vote up
DashboardPage = () => {
  // state hook for a new room name
  // const [showCreateNewRoomModal, setShowCreateNewRoomModal] = useState(false);

  const classes = useStyles();
  const [allRooms, setAllRooms] = useState([]);
  const [open, setOpen] = useState(false);

  const toggleOpen = e => {
    e.preventDefault();
    setOpen(!open);
  };

  useEffect(() => {
    axios
      .get('/api/v1/rooms')
      .then(function (response) {
        const rooms = [];
        for (let i = 0; i < response.data.length; i += 1) {
          console.log('The Room Data', response.data[i]);
          if (response.data[i].active) {
            rooms.push(
              <div className="dashboard-box">
                <RoomOption room={response.data[i]} key={i} />
              </div>
            );
          }
        }
        setAllRooms(rooms);
      })
      .catch(function (error) {
        console.log(error);
      });
  }, []);

  return (
    <div className="dashboard-page">
      <div className="page-header">
        <h1 className="lobby">Lobby</h1>
      </div>
      <div className="create-room">
        <button type="submit" onClick={toggleOpen}>
          Create Room
        </button>
      </div>
      <Modal open={open} onClose={toggleOpen} className={classes.modal}>
        <div className={classes.paper}>
          <CreateNewRoomModal />
        </div>
      </Modal>
      <div className="dashboard-container">{allRooms}</div>
    </div>
  );
}
Example #10
Source File: styled.js    From yi-note with GNU General Public License v3.0 5 votes vote down vote up
StyledModal = styled(Modal)`
  display: flex;
  align-items: center;
  justify-content: center;
`
Example #11
Source File: SetIncome.js    From Simplify-Testing-with-React-Testing-Library with MIT License 5 votes vote down vote up
render() {
    const { classes } = this.props;
    const { open, income } = this.state;
    return (
      <Fragment>
        <Button
          variant='contained'
          className={classes.newIncomeBtn}
          color='secondary'
          onClick={this.handleOpen}
        >
          Set Income
        </Button>
        <Modal
          aria-labelledby='Set Income Amount '
          aria-describedby="Set's the income amount"
          open={open}
          onClose={this.handleClose}
        >
          <div className={classes.paper}>
            <Typography variant='body1' id='modal-title'>
              Enter you total income.
            </Typography>

            <FormControl
              style={{
                display: 'block',
                marginTop: '10px',
                marginBottom: '20px',
              }}
            >
              <InputLabel htmlFor='adornment-amount'>Amount</InputLabel>
              <Input
                type='number'
                placeholder='Enter a number'
                onChange={this.handleChange}
                startAdornment={
                  <InputAdornment position='start'>$</InputAdornment>
                }
              />
            </FormControl>
            <Button
              disabled={income <= 0 ? true : false}
              fullWidth
              variant='contained'
              color='secondary'
              onClick={this.handleSetIncome}
            >
              Submit
            </Button>
          </div>
        </Modal>
      </Fragment>
    );
  }
Example #12
Source File: CreateNewBudget.js    From Simplify-Testing-with-React-Testing-Library with MIT License 5 votes vote down vote up
render() {
    const { classes } = this.props;
    const { open, category, amount } = this.state;
    return (
      <Fragment>
        <Button
          variant='contained'
          className={classes.newBudgetBtn}
          color='primary'
          onClick={this.handleOpen}
        >
          Create New Budget
        </Button>
        <Modal
          aria-labelledby='Create New Budget'
          aria-describedby="Create's a new budget"
          open={open}
          onClose={this.handleClose}
        >
          <div className={classes.paper}>
            <Typography variant='body1' id='modal-title'>
              Select a category and enter a budget amount.
            </Typography>

            <FormControl
              style={{
                width: '181px',
                marginTop: '10px',
                marginBottom: '20px',
              }}
            >
              <InputLabel htmlFor='category-native-simple'>Category</InputLabel>
              <Select
                native
                value={category}
                onChange={this.handleChange}
                inputProps={{
                  name: 'category',
                  id: 'category-native-simple',
                }}
              >
                <option value='' />
                {this.renderBudgetOptions()}
              </Select>
            </FormControl>

            <FormControl style={{ display: 'block', marginBottom: '20px' }}>
              <InputLabel htmlFor='adornment-amount'>Amount</InputLabel>
              <Input
                type='number'
                inputProps={{
                  name: 'amount',
                  id: 'amount-native-simple',
                }}
                placeholder='Enter a number'
                onChange={this.handleChange}
                startAdornment={
                  <InputAdornment position='start'>$</InputAdornment>
                }
              />
              <Typography color='error' variant='body1'>
                * Budgets must be in increments of 5. {<br />}* Amounts less
                than 5 will default to $5.
              </Typography>
            </FormControl>
            <Button
              disabled={amount && category ? false : true}
              fullWidth
              variant='contained'
              color='secondary'
              onClick={this.handleAddNewBudget}
            >
              Add Budget
            </Button>
          </div>
        </Modal>
      </Fragment>
    );
  }
Example #13
Source File: SetIncome.js    From Simplify-Testing-with-React-Testing-Library with MIT License 5 votes vote down vote up
render() {
    const { classes } = this.props;
    const { open, income } = this.state;
    return (
      <Fragment>
        <MuiThemeProvider theme={addIncomeBtnTheme}>
          <Button
            variant='contained'
            className={classes.newIncomeBtn}
            color='secondary'
            onClick={this.handleOpen}
          >
            Set Income
          </Button>
        </MuiThemeProvider>
        <Modal
          aria-labelledby='Set Income Amount '
          aria-describedby="Set's the income amount"
          open={open}
          onClose={this.handleClose}
        >
          <div className={classes.paper}>
            <Typography variant='body1' id='modal-title'>
              Enter you total income.
            </Typography>

            <FormControl
              style={{
                display: 'block',
                marginTop: '10px',
                marginBottom: '20px',
              }}
            >
              <InputLabel htmlFor='adornment-amount'>Amount</InputLabel>
              <Input
                type='number'
                placeholder='Enter a number'
                onChange={this.handleChange}
                startAdornment={
                  <InputAdornment position='start'>$</InputAdornment>
                }
              />
            </FormControl>
            <MuiThemeProvider theme={addIncomeBtnTheme}>
              <Button
                disabled={income <= 0 ? true : false}
                fullWidth
                variant='contained'
                color='secondary'
                onClick={this.handleSetIncome}
              >
                Submit
              </Button>
            </MuiThemeProvider>
          </div>
        </Modal>
      </Fragment>
    );
  }
Example #14
Source File: CreateNewBudget.js    From Simplify-Testing-with-React-Testing-Library with MIT License 5 votes vote down vote up
render() {
    const { classes } = this.props;
    const { open, category, amount } = this.state;
    return (
      <Fragment>
        <Button
          variant='contained'
          className={classes.newBudgetBtn}
          color='primary'
          onClick={this.handleOpen}
        >
          Create New Budget
        </Button>
        <Modal
          aria-labelledby='Create New Budget'
          aria-describedby="Create's a new budget"
          open={open}
          onClose={this.handleClose}
        >
          <div className={classes.paper}>
            <Typography variant='body1' id='modal-title'>
              Select a category and enter a budget amount.
            </Typography>

            <FormControl
              style={{
                width: '181px',
                marginTop: '10px',
                marginBottom: '20px',
              }}
            >
              <InputLabel htmlFor='category-native-simple'>Category</InputLabel>
              <Select
                native
                value={category}
                onChange={this.handleChange}
                inputProps={{
                  name: 'category',
                  id: 'category-native-simple',
                }}
              >
                <option value='' />
                {this.renderBudgetOptions()}
              </Select>
            </FormControl>

            <FormControl style={{ display: 'block', marginBottom: '20px' }}>
              <InputLabel htmlFor='adornment-amount'>Amount</InputLabel>
              <Input
                type='number'
                inputProps={{
                  name: 'amount',
                  id: 'amount-native-simple',
                }}
                placeholder='Enter a number'
                onChange={this.handleChange}
                startAdornment={
                  <InputAdornment position='start'>$</InputAdornment>
                }
              />
              <Typography color='error' variant='body1'>
                * Budgets must be in increments of 5. {<br />}* Amounts less
                than 5 will default to $5.
              </Typography>
            </FormControl>
            <Button
              disabled={amount && category ? false : true}
              fullWidth
              variant='contained'
              color='secondary'
              onClick={this.handleAddNewBudget}
            >
              Add Budget
            </Button>
          </div>
        </Modal>
      </Fragment>
    );
  }
Example #15
Source File: DeleteCollege.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
DeleteZone = props => {
  const [open, setOpen] = React.useState(false);
  const [formState, setFormState] = useState({
    isDeleteData: false,
    isValid: false,
    stateCounter: 0,
    values: {},
    dataToDelete: {}
  });

  if (props.showModal && !formState.stateCounter) {
    formState.stateCounter = 0;
    formState.values[COLLEGE_ID] = props.id;
    formState.isDeleteData = false;
    formState.dataToDelete = props.dataToDelete;
  }

  const handleCloseModal = (message = "") => {
    /** This event handles the scenario when the pop up is closed just by clicking outside the popup 
    to ensure that only string value is passed to message variable */
    if (typeof message !== "string") {
      message = "";
    }
    setFormState(formState => ({
      ...formState,
      values: {},
      isDeleteData: false,
      isValid: false,
      stateCounter: 0
    }));
    if (formState.isDeleteData) {
      props.closeModal(true, message);
    } else {
      props.closeModal(false, message);
    }
  };

  const handleSubmit = async event => {
    /** CALL Put FUNCTION */
    setOpen(true);
    event.preventDefault();
    event.persist();
    props.clearSelectedRow(true);
    let status = {};
    /** Calls checkIfStateCanBeDelete function to check whether the state can be deleted
     and returns back an opbject with status and message*/
    if (props.isMultiDelete) {
      status = await checkIfMultiCollegeCanBeDelete();
    } else {
      status = await checkIfCollegeCanBeDelete(
        formState.dataToDelete.organizationId
      );
    }
    setOpen(false);
    if (status["status"]) {
      deleteData();
    } else {
      formState.isDeleteData = false;
      handleCloseModal(
        status["message"]
      ); /** returns back a message saying state cannot be deleted */
    }
  };

  const handleClose = async event => {
    props.clearSelectedRow(true);
    props.closeModal();
  };

  const checkIfMultiCollegeCanBeDelete = async () => {
    let dataToSent = {};
    let isErrorCounter = 0;
    for (let i in props.MultiOrganizationId) {
      let status = await checkIfCollegeCanBeDelete(
        props.MultiOrganizationId[i]
      );
      if (!status["status"]) {
        isErrorCounter += 1;
        break;
      }
    }
    if (isErrorCounter > 0) {
      dataToSent = {
        status: false,
        message: "Error deleting selected Colleges"
      };
    } else {
      dataToSent = { status: true, message: "Success" };
    }
    return dataToSent;
  };

  /** This checks if the state can be deleted and returns back an array with status and message*/
  const checkIfCollegeCanBeDelete = async id => {
    let dataToReturn = {};
    let studentsCheckUrl =
      strapiConstants.STRAPI_DB_URL +
      strapiConstants.STRAPI_COLLEGES +
      "/" +
      id +
      "/" +
      strapiConstants.STRAPI_STUDENT;
    await serviceProviders
      .serviceProviderForGetRequest(studentsCheckUrl)
      .then(res => {
        if (res.data.result.length > 0) {
          dataToReturn = {
            status: false,
            message:
              "Cannot delete College " +
              formState.dataToDelete["name"] +
              " as it is linked to other Students"
          };
        } else {
          dataToReturn = {
            status: true,
            message: "Success"
          };
        }
      })
      .catch(error => {
        console.log("error", error);
        /** return error */
        dataToReturn = {
          status: false,
          message: "Error deleting College " + formState.dataToDelete["name"]
        };
      });
    return dataToReturn;
  };

  const deleteData = () => {
    if (props.isMultiDelete) {
      let deleteId = {
        ids: props.id
      };
      serviceProviders
        .serviceProviderForPostRequest(COLLEGE_URL, deleteId)
        .then(res => {
          setFormState(formState => ({
            ...formState,
            isValid: true
          }));
          formState.isDeleteData = true;
          handleCloseModal("Colleges have been deleted successfully");
        })
        .catch(error => {
          console.log("error");
          formState.isDeleteData = false;
          handleCloseModal(
            "An error has occured while deleting colleges. Kindly, try again"
          );
        });
    } else {
      let idArray = [];
      idArray.push(parseInt(props.id));
      let deleteId = {
        ids: idArray
      };
      serviceProviders
        .serviceProviderForPostRequest(COLLEGE_URL, deleteId)
        .then(res => {
          setFormState(formState => ({
            ...formState,
            isValid: true
          }));
          formState.isDeleteData = true;
          handleCloseModal(
            "College " +
              formState.dataToDelete["name"] +
              " has been deleted successfully"
          );
        })
        .catch(error => {
          console.log("error", error);
          formState.isDeleteData = false;
          handleCloseModal(
            "An error has occured while deleting college" +
              formState.dataToDelete["name"] +
              ". Kindly, try again"
          );
        });
    }
  };

  const classes = useStyles();
  return (
    <Modal
      aria-labelledby="transition-modal-title"
      aria-describedby="transition-modal-description"
      className={classes.modal}
      open={props.showModal}
      onClose={handleCloseModal}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={props.showModal}>
        <div className={classes.paper}>
          <div className={classes.blockpanel}>
            <Typography variant={"h2"} className={classes.textMargin}>
              {genericConstants.DELETE_TEXT}
            </Typography>
            <div className={classes.crossbtn}>
              <IconButton
                aria-label="close"
                className={classes.closeButton}
                onClick={props.modalClose}
              >
                <CloseIcon />
              </IconButton>
            </div>
          </div>
          <div className={classes.edit_dialog}>
            <Grid item xs={12}>
              <Grid container spacing={2} alignItems="center">
                <Grid item lg className={classes.deletemessage}>
                  {props.isMultiDelete
                    ? "Are you sure you want to delete the selected Colleges?"
                    : "Are you sure you want to delete College " +
                      formState.dataToDelete["name"] +
                      "?"}
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12}>
              <Grid
                container
                direction="row"
                justify="flex-end"
                alignItems="center"
                spacing={2}
              >
                <Grid item>
                  <YellowButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleSubmit}
                  >
                    Ok
                  </YellowButton>
                </Grid>
                <Grid item>
                  <GrayButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleClose}
                  >
                    Close
                  </GrayButton>
                </Grid>
              </Grid>
            </Grid>
          </div>
          <Backdrop className={classes.backdrop} open={open}>
            <CircularProgress color="inherit" />
          </Backdrop>
        </div>
      </Fade>
    </Modal>
  );
}
Example #16
Source File: BlockUnblockCollege.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
BlockUnblockCollege = props => {
  const [open, setOpen] = React.useState(false);
  const [formState, setFormState] = useState({
    isDataBlockUnblock: false,
    isValid: false,
    stateCounter: 0
  });

  /** Part for editing college */
  if (props.showModal && !formState.stateCounter) {
    formState.stateCounter = 0;
    formState.isDataBlockUnblock = false;
  }

  const handleCloseModal = (message = "") => {
    setOpen(false);
    /** This event handles the scenario when the pop up is closed just by clicking outside the popup 
    to ensure that only string value is passed to message variable */
    if (typeof message !== "string") {
      message = "";
    }
    setFormState(formState => ({
      ...formState,
      values: {},
      isDataBlockUnblock: false,
      isValid: false,
      stateCounter: 0
    }));
    if (formState.isDataBlockUnblock) {
      props.closeModal(true, message);
    } else {
      props.closeModal(false, message);
    }
  };

  const handleSubmit = async event => {
    /** CALL Put FUNCTION */
    setOpen(true);
    event.preventDefault();
    event.persist();
    props.clearSelectedRow(true);
    /** Calls checkIfStateCanBeDelete function to check whether the state can be deleted
     and returns back an opbject with status and message*/
    blockUnblockData();
  };

  const blockUnblockData = () => {
    if (props.isMultiBlock || props.isMultiUnblock) {
      let COLLEGE_URL = "";
      if (props.isMultiUnblock) {
        COLLEGE_URL = COLLEGE_UNBLOCK_URL;
      } else {
        COLLEGE_URL = COLLEGE_BLOCK_URL;
      }
      let postData = {
        ids: props.multiBlockCollegeIds
      };
      serviceProviders
        .serviceProviderForPostRequest(COLLEGE_URL, postData)
        .then(res => {
          setFormState(formState => ({
            ...formState,
            isValid: true
          }));
          formState.isDataBlockUnblock = true;
          if (props.isMultiUnblock) {
            handleCloseModal("Colleges have been unblocked successfully");
          } else {
            handleCloseModal("Colleges have been blocked successfully");
          }
        })
        .catch(error => {
          console.log("error");
          formState.isDataBlockUnblock = false;
          if (props.isMultiUnblock) {
            handleCloseModal(
              "An error has occured while unblocking colleges. Kindly, try again."
            );
          } else {
            handleCloseModal(
              "An error has occured while blocking colleges. Kindly, try again."
            );
          }
        });
    } else {
      if (props.dataToBlockUnblock["is_blocked"]) {
        let ids = [];
        ids.push(props.dataToBlockUnblock["id"]);
        let postData = {
          ids: ids
        };
        serviceProviders
          .serviceProviderForPostRequest(COLLEGE_UNBLOCK_URL, postData)
          .then(res => {
            setFormState(formState => ({
              ...formState,
              isValid: true
            }));
            formState.isDataBlockUnblock = true;
            handleCloseModal(
              "College " +
                props.dataToBlockUnblock["name"] +
                " has been unblocked."
            );
          })
          .catch(error => {
            console.log("error");
            formState.isDataBlockUnblock = false;
            handleCloseModal(
              "An error has occured while unblocking college" +
                props.dataToBlockUnblock["name"] +
                ". Kindly, try again."
            );
          });
      } else {
        let ids = [];
        ids.push(props.dataToBlockUnblock["id"]);
        let postData = {
          ids: ids
        };
        serviceProviders
          .serviceProviderForPostRequest(COLLEGE_BLOCK_URL, postData)
          .then(res => {
            setFormState(formState => ({
              ...formState,
              isValid: true
            }));
            formState.isDataBlockUnblock = true;
            handleCloseModal(
              "College " +
                props.dataToBlockUnblock["name"] +
                " has been blocked."
            );
          })
          .catch(error => {
            console.log("error");
            formState.isDataBlockUnblock = false;
            handleCloseModal(
              "An error has occured while blocking college" +
                props.dataToBlockUnblock["name"] +
                ". Kindly, try again."
            );
          });
      }
    }
  };

  const handleBlock = async event => {
    props.clearSelectedRow(true);
    props.closeModal();
  };

  const classes = useStyles();
  return (
    <React.Fragment>
      {!formUtilities.checkEmpty(props.dataToBlockUnblock) ||
      props.multiBlockCollegeIds.length ? (
        <Modal
          aria-labelledby="transition-modal-title"
          aria-describedby="transition-modal-description"
          className={classes.modal}
          open={props.showModal}
          onClose={handleCloseModal}
          closeAfterTransition
          BackdropComponent={Backdrop}
          BackdropProps={{
            timeout: 500
          }}
        >
          <Fade in={props.showModal}>
            <div className={classes.paper}>
              <div className={classes.blockpanel}>
                <Typography variant={"h2"} className={classes.textMargin}>
                  {props.isMultiBlock || props.isMultiUnblock
                    ? props.isMultiBlock
                      ? genericConstants.BLOCK_BUTTON_TEXT
                      : genericConstants.UNBLOCK_BUTTON_TEXT
                    : null}
                  {!props.isMultiBlock && !props.isMultiUnblock
                    ? props.dataToBlockUnblock["is_blocked"]
                      ? genericConstants.UNBLOCK_BUTTON_TEXT
                      : genericConstants.BLOCK_BUTTON_TEXT
                    : null}
                </Typography>
                <div className={classes.crossbtn}>
                  <IconButton
                    aria-label="close"
                    className={classes.closeButton}
                    onClick={props.modalClose}
                  >
                    <CloseIcon />
                  </IconButton>
                </div>
              </div>
              <div className={classes.edit_dialog}>
                <Grid item xs={12}>
                  <Grid container spacing={2} alignItems="center">
                    <Grid item lg className={classes.deletemessage}>
                      {props.isMultiBlock || props.isMultiUnblock
                        ? props.isMultiBlock
                          ? "Are you sure you want to block all selected colleges"
                          : "Are you sure you want to unblock all selected colleges"
                        : null}
                      {!props.isMultiBlock && !props.isMultiUnblock
                        ? props.dataToBlockUnblock["is_blocked"]
                          ? "Are you sure you want to unblock college " +
                            props.dataToBlockUnblock["name"]
                          : "Are you sure you want to block college " +
                            props.dataToBlockUnblock["name"]
                        : null}
                    </Grid>
                  </Grid>
                </Grid>
                <Grid item xs={12}>
                  <Grid
                    container
                    direction="row"
                    justify="flex-end"
                    alignItems="center"
                    spacing={2}
                  >
                    <Grid item>
                      <YellowButton
                        type="submit"
                        color="primary"
                        variant="contained"
                        onClick={handleSubmit}
                      >
                        OK
                      </YellowButton>
                    </Grid>
                    <Grid item>
                      <GrayButton
                        type="submit"
                        color="primary"
                        variant="contained"
                        onClick={handleBlock}
                      >
                        Close
                      </GrayButton>
                    </Grid>
                  </Grid>
                </Grid>
              </div>
              <Backdrop className={classes.backdrop} open={open}>
                <CircularProgress color="inherit" />
              </Backdrop>
            </div>
          </Fade>
        </Modal>
      ) : null}
    </React.Fragment>
  );
}
Example #17
Source File: index.jsx    From Pandaudio with MIT License 4 votes vote down vote up
RoomPage = props => {
  const {
    location: {
      state: { isHost, roomInfo },
    },
  } = props;

  const classes = useStyles();
  const [open, setOpen] = useState(false);
  const [songQueueReady, setSongQueueReady] = useState(false);
  const [initialPlay, setInitialPlay] = useState(false);
  const dispatch = useDispatch();
  const store = useStore();
  const playerState = useSelector(state => state.player);
  const songQueueState = useSelector(state => state.songQueue);
  // hard coded pokemon song

  useEffect(() => {
    // setup fetch data method when component loads intially
    setup();

    // join song room when page is loaded is loaded
    socket.emit('join_room', `song${roomInfo.id}`);

    // onload of room post message to websocket asking for the current song URI and time
    if (!isHost) {
      socket.emit('requestPlayInfo', {
        room: `song${roomInfo.id}`,
        targetGuest: socket.id,
      });
    }

    if (isHost) {
      socket.on('requestPlayInfo', data => {
        // emit a special play message back to ONLY that guest requester
        console.log('host receive requests for play Info', data);
        getPlayerInfoAndEmit(window.globalSpotifyPlayer, data);
      });
    }

    // add listeners of websocket to play a song at a certain time
    socket.on('play', data => {
      console.log('Incoming play message: ', data);

      // only play song if the targetGuest is my own socket.id or if its falsy (broadcast to everyone to play)
      if (data.targetGuest === socket.id || !data.targetGuest) {
        playSong(window.globalSpotifyPlayer, data.spotify_uris, data.start_time);
      }
    });

    // add listener of websocket to pause a song
    socket.on('pause', data => {
      console.log('Incoming message: ', data);
      pauseSong(window.globalSpotifyPlayer);
    });
  }, []);

  const setup = () => {
    // async call to get all songs and dispatch to songQueue store

    fetch(`/api/v1/rooms/${roomInfo.id}/songs`, {
      method: 'GET',
      headers: {
        'Content-Type': 'appplication/json',
      },
    })
      .then(response => response.json())
      .then(data => {
        console.log('grabbed all the songs from db', data);
        dispatch({ type: SONG_QUEUE_UPDATE, payload: data });
        setSongQueueReady(true);
      });
  };

  const getPlayerInfoAndEmit = (player, requestData) => {
    const {
      _options: { getOAuthToken },
    } = player;

    getOAuthToken(access_token => {
      fetch(`https://api.spotify.com/v1/me/player`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${access_token}`,
        },
      })
        .then(response => response.json())
        .then(playerInfo => {
          const {
            item: { uri },
            progress_ms,
          } = playerInfo;

          const trackWindow = store.getState().player.data.track_window;
          const currentTrack = trackWindow.current_track;
          const nextTracks = trackWindow.next_tracks;
          const tracks = [currentTrack, ...nextTracks];

          socket.emit('play', {
            room: `song${roomInfo.id}`,
            spotify_uris: tracks.map(track => track.uri),
            start_time: progress_ms,
            targetGuest: requestData.targetGuest,
          });
        });
    });
  };

  // helper to play a song
  const playSong = (player, spotify_uris, start_time) => {
    // function to play song from spotify API
    const play = ({
      spotify_uris,
      playerInstance: {
        _options: { getOAuthToken, id },
      },
      start_time = 0,
    }) => {
      getOAuthToken(access_token => {
        console.log('we are in the get oauth', access_token, id);
        console.log('this is the spotify uri', spotify_uris);
        fetch(`https://api.spotify.com/v1/me/player/play?device_id=${id}`, {
          method: 'PUT',
          body: JSON.stringify({ uris: spotify_uris, position_ms: start_time }),
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${access_token}`,
          },
        });
      });
    };

    console.log('before we call play', player);

    play({
      playerInstance: player,
      spotify_uris,
      start_time,
    });
  };

  const pauseSong = player => {
    player.pause().then(() => {
      console.log('Paused!');
    });
  };

  const handlePlay = e => {
    let uris;

    if (!initialPlay) {
      uris = songQueueState.data.map(song => song.uri);
      setInitialPlay(true);
    } else {
      const trackWindow = store.getState().player.data.track_window;
      const currentTrack = trackWindow.current_track;
      const nextTracks = trackWindow.next_tracks;
      const tracks = [currentTrack, ...nextTracks];

      uris = tracks.map(track => track.uri);
    }

    socket.emit('play', {
      room: `song${roomInfo.id}`,
      spotify_uris: uris,
      start_time: playerState.data.position || 0,
    });
  };

  const handlePause = e => {
    socket.emit('pause', {
      room: `song${roomInfo.id}`,
    });
  };

  const toggleOpen = e => {
    e.preventDefault();
    setOpen(!open);
  };

  const { location } = props;
  const { track_window } = playerState.data;

  let songName, artists, albumName, albumArt, isPaused;

  if (track_window) {
    songName = track_window.current_track.name;
    artists = track_window.current_track.artists;
    albumName = track_window.current_track.album.name;
    albumArt = track_window.current_track.album.images[0].url;
    isPaused = playerState.data.paused;
  }

  return (
    <div className="room-page">
      <div className="room-content">
        {location.state.isHost ? (
          <div className="addsong-container">
            <button className="btn-addsong" type="submit" onClick={toggleOpen}>
              Add Song
            </button>
            <HostDisableRoomButton roomId={location.state.roomInfo.id} />
            <Modal open={open} onClose={toggleOpen} className={classes.modal}>
              <div className={classes.paper}>
                <SongSearch roomId={location.state.roomInfo.id} />
              </div>
            </Modal>
          </div>
        ) : null}
        <div className="room-header">
          <h2>{roomInfo.room_name}</h2>
          <p>Back to Lobby</p>
        </div>
        <div className="room-player">
          <div className="player-cover">
            {albumArt && <img src={albumArt} />}
          </div>
          <div className="player-content">
            <div className="player-playing">
              <p>{!track_window ? 'Waiting for tunes' : isPaused ? 'Paused' : 'Now Playing'}</p>
            </div>
            <div className="player-details">
              <h3>{songName || 'Song Name'}</h3>
              <p>{albumName || 'Album Name'}</p>
              <p>0:00 / 2:30</p>
            </div>
            <div className="player-btn">
              {isHost && playerState.ready && songQueueReady ? (
                <PlaybackControls
                  playSong={() => {
                    handlePlay();
                  }}
                  pauseSong={() => {
                    handlePause();
                  }}
                />
              ) : null}
            </div>
          </div>
        </div>
      </div>
      <div className="sidebar">
        <div className="room-queue">
          <h1>Song Queue</h1>
        </div>
        <div className="room-chat">
          <Chat roomId={roomInfo.id} />
        </div>
      </div>
    </div>
  );
}
Example #18
Source File: DeleteEvent.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
DeleteUser = props => {
  const { setLoaderStatus } = useContext(LoaderContext);
  const [formState, setFormState] = useState({
    isDeleteData: false,
    isValid: false,
    stateCounter: 0,
    values: {},
    dataToDelete: {}
  });

  if (props.showModal && !formState.stateCounter) {
    formState.stateCounter = 0;
    formState.values[EVENT_ID] = props.id;
    formState.isDeleteData = false;
    formState.dataToDelete = props.dataToDelete;
  }
  const handleCloseModal = (message = "") => {
    /** This event handles the scenario when the pop up is closed just by clicking outside the popup 
    to ensure that only string value is passed to message variable */
    if (typeof message !== "string") {
      message = "";
    }
    setFormState(formState => ({
      ...formState,
      values: {},
      isDeleteData: false,
      isValid: false,
      stateCounter: 0
    }));
    if (formState.isDeleteData) {
      props.closeModal(true, message);
    } else {
      props.closeModal(false, message);
    }
  };

  const handleSubmit = event => {
    /** CALL Put FUNCTION */
    setLoaderStatus(true);
    props.clearSelectedRow(true);
    deleteData();
    event.preventDefault();
  };

  const deleteData = () => {
    if (props.isMultiDelete) {
      serviceProviders
        .serviceProviderForAllDeleteRequest(EVENT_URL, props.id)
        .then(res => {
          setLoaderStatus(false);
          setFormState(formState => ({
            ...formState,
            isValid: true
          }));
          formState.isDeleteData = true;
          handleCloseModal("Events has been deleted successfully");
        })
        .catch(error => {
          setLoaderStatus(false);
          console.log("error", error);
          formState.isDeleteData = false;
          handleCloseModal(
            "An error has occured while deleting events. Kindly, try again"
          );
        });
    } else {
      serviceProviders
        .serviceProviderForDeleteRequest(EVENT_URL, props.id)
        .then(res => {
          setLoaderStatus(false);
          setFormState(formState => ({
            ...formState,
            isValid: true
          }));
          formState.isDeleteData = true;
          handleCloseModal(
            "Event " +
              formState.dataToDelete["name"] +
              " has been deleted successfully"
          );
        })
        .catch(error => {
          setLoaderStatus(false);
          console.log("error");
          formState.isDeleteData = false;
          handleCloseModal(
            "An error has occured while deleting event" +
              formState.dataToDelete["name"] +
              ". Kindly, try again"
          );
        });
    }
  };

  const handleClose = async event => {
    props.clearSelectedRow(true);
    props.closeModal();
  };

  const classes = useStyles();
  return (
    <Modal
      aria-labelledby="transition-modal-title"
      aria-describedby="transition-modal-description"
      className={classes.modal}
      open={props.showModal}
      onClose={handleCloseModal}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={props.showModal}>
        <div className={classes.paper}>
          <div className={classes.blockpanel}>
            <Typography variant={"h2"} className={classes.textMargin}>
              {genericConstants.DELETE_TEXT}
            </Typography>
            <div className={classes.crossbtn}>
              <IconButton
                aria-label="close"
                className={classes.closeButton}
                onClick={props.modalClose}
              >
                <CloseIcon />
              </IconButton>
            </div>
          </div>
          <div className={classes.edit_dialog}>
            <Grid item xs={12}>
              <Grid container spacing={2} alignItems="center">
                <Grid item lg className={classes.deletemessage}>
                  {props.id ? (
                    props.isMultiDelete ? (
                      <p>
                        Are you sure you want to delete "{props.seletedUser}"
                        Events?
                      </p>
                    ) : (
                      <p>
                        Are you sure you want to delete event "
                        {props.dataToDelete["name"]}"?
                      </p>
                    )
                  ) : null}
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12}>
              <Grid
                container
                direction="row"
                justify="flex-end"
                alignItems="center"
                spacing={2}
              >
                <Grid item>
                  <YellowButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleSubmit}
                  >
                    Ok
                  </YellowButton>
                </Grid>
                <Grid item>
                  <GrayButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleClose}
                  >
                    Close
                  </GrayButton>
                </Grid>
              </Grid>
            </Grid>
          </div>
        </div>
      </Fade>
    </Modal>
  );
}
Example #19
Source File: HireStudent.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
HireStudent = props => {
  const [open, setOpen] = React.useState(false);

  const [formState, setFormState] = useState({
    isStudentHired: false,
    isValid: false,
    stateCounter: 0,
    values: {}
  });

  const handleCloseModal = () => {
    setOpen(false);

    setFormState(formState => ({
      ...formState,
      values: {},
      isStudentHired: false,
      isValid: false,
      stateCounter: 0
    }));

    if (formState.isStudentHired) {
      props.closeHireModal(true);
    } else {
      props.closeHireModal(false);
    }
  };

  const handleSubmit = event => {
    setOpen(true);
    /** CALL Put FUNCTION */
    studentHired();
    event.preventDefault();
  };

  const studentHired = () => {
    var body;
    if (props.isHired) {
      body = {
        is_hired_at_event: true
      };
    }
    if (props.isUnHired) {
      body = {
        is_hired_at_event: false
      };
    }
    serviceProviders
      .serviceProviderForPutRequest(REGISTRATION_URL, props.id, body)
      .then(res => {
        formState.isStudentHired = true;
        handleCloseModal();
      })
      .catch(error => {
        console.log("error---", error);
        formState.isStudentHired = false;
        handleCloseModal();
      });
  };

  const classes = useStyles();
  return (
    <Modal
      aria-labelledby="transition-modal-title"
      aria-describedby="transition-modal-description"
      className={classes.modal}
      open={props.showModal}
      onClose={handleCloseModal}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={props.showModal}>
        <div className={classes.paper}>
          <div className={classes.blockpanel}>
            <Typography variant={"h2"} className={classes.textMargin}>
              {props.isHired
                ? genericConstants.HIRE_BUTTON_TEXT
                : genericConstants.DEHIRE_BUTTON_TEXT}
            </Typography>
            <div className={classes.crossbtn}>
              <IconButton
                aria-label="close"
                className={classes.closeButton}
                onClick={props.modalClose}
              >
                <CloseIcon />
              </IconButton>
            </div>
          </div>
          <div className={classes.edit_dialog}>
            <Grid item xs={12}>
              <Grid container spacing={2} alignItems="center">
                <Grid item lg className={classes.deletemessage}>
                  {props.isHired ? (
                    <p>Are you sure you want to Hire {props.studentName}?</p>
                  ) : (
                    <p>Are you sure you want to Dehire {props.studentName}?</p>
                  )}
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12}>
              <Grid
                container
                direction="row"
                justify="flex-end"
                alignItems="center"
                spacing={2}
              >
                <Grid item>
                  <YellowButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleSubmit}
                  >
                    Ok
                  </YellowButton>
                </Grid>
                <Grid item>
                  <GrayButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={props.modalClose}
                  >
                    Close
                  </GrayButton>
                </Grid>
              </Grid>
            </Grid>
          </div>
          <Backdrop className={classes.backdrop} open={open}>
            <CircularProgress color="inherit" />
          </Backdrop>
        </div>
      </Fade>
    </Modal>
  );
}
Example #20
Source File: MarkAttaindance.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
MarkAttaindance = props => {
  const [open, setOpen] = React.useState(false);

  const [formState, setFormState] = useState({
    isAttaindanceMarked: false,
    isValid: false,
    stateCounter: 0,
    values: {}
  });

  const handleCloseModal = () => {
    setOpen(false);

    setFormState(formState => ({
      ...formState,
      values: {},
      isAttaindanceMarked: false,
      isValid: false,
      stateCounter: 0
    }));

    if (formState.isAttaindanceMarked) {
      props.closeAttaindanceModal(true);
    } else {
      props.closeAttaindanceModal(false);
    }
  };

  const handleSubmit = event => {
    setOpen(true);
    /** CALL Put FUNCTION */
    attaindanceHandler();
    event.preventDefault();
  };

  const attaindanceHandler = () => {
    var body;
    if (props.isPresent) {
      body = {
        is_attendance_verified: true
      };
    }
    if (props.isAbsent) {
      body = {
        is_attendance_verified: false
      };
    }
    serviceProviders
      .serviceProviderForPutRequest(REGISTRATION_URL, props.id, body)
      .then(res => {
        formState.isAttaindanceMarked = true;
        handleCloseModal();
      })
      .catch(error => {
        console.log("error---", error);
        formState.isAttaindanceMarked = false;
        handleCloseModal();
      });
  };
  const classes = useStyles();
  return (
    <Modal
      aria-labelledby="transition-modal-title"
      aria-describedby="transition-modal-description"
      className={classes.modal}
      open={props.showModal}
      onClose={handleCloseModal}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={props.showModal}>
        <div className={classes.paper}>
          <div className={classes.blockpanel}>
            <Typography variant={"h2"} className={classes.textMargin}>
              {props.isPresent
                ? genericConstants.ADD_ATT_BUTTON_TEXT
                : genericConstants.REMOVE_ATT_BUTTON_TEXT}
            </Typography>
            <div className={classes.crossbtn}>
              <IconButton
                aria-label="close"
                className={classes.closeButton}
                onClick={props.modalClose}
              >
                <CloseIcon />
              </IconButton>
            </div>
          </div>
          <div className={classes.edit_dialog}>
            <Grid item xs={12}>
              <Grid container spacing={2} alignItems="center">
                <Grid item lg className={classes.deletemessage}>
                  {props.isPresent ? (
                    <p>
                      Are you sure you want to add attendence for{" "}
                      {props.studentName}?
                    </p>
                  ) : (
                    <p>
                      Are you sure you want to remove attendence for{" "}
                      {props.studentName}?
                    </p>
                  )}
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12}>
              <Grid
                container
                direction="row"
                justify="flex-end"
                alignItems="center"
                spacing={2}
              >
                <Grid item>
                  <YellowButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleSubmit}
                  >
                    Ok
                  </YellowButton>
                </Grid>
                <Grid item>
                  <GrayButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={props.modalClose}
                  >
                    Close
                  </GrayButton>
                </Grid>
              </Grid>
            </Grid>
          </div>
          <Backdrop className={classes.backdrop} open={open}>
            <CircularProgress color="inherit" />
          </Backdrop>
        </div>
      </Fade>
    </Modal>
  );
}
Example #21
Source File: CardModal.js    From TrelloClone with MIT License 4 votes vote down vote up
CardModal = ({ cardId, open, setOpen, card, list }) => {
  const classes = useStyles();
  const [title, setTitle] = useState(card.title);
  const [description, setDescription] = useState(card.description);
  const dispatch = useDispatch();

  useEffect(() => {
    setTitle(card.title);
    setDescription(card.description);
  }, [card]);

  const onTitleDescriptionSubmit = async (e) => {
    e.preventDefault();
    dispatch(editCard(cardId, { title, description }));
  };

  const onArchiveCard = async () => {
    dispatch(archiveCard(cardId, true));
    setOpen(false);
  };

  return (
    <Modal open={open} onClose={() => setOpen(false)}>
      <div className={`${classes.paper} ${classes.cardModal}`}>
        <form onSubmit={(e) => onTitleDescriptionSubmit(e)}>
          <div className={classes.modalTop}>
            <TextField
              variant='outlined'
              margin='normal'
              required
              fullWidth
              multiline
              label='Card title'
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && onTitleDescriptionSubmit(e)}
              className={classes.cardTitle}
            />
            <Button onClick={() => setOpen(false)}>
              <CloseIcon />
            </Button>
          </div>
          <TextField
            variant='outlined'
            margin='normal'
            fullWidth
            multiline
            label='Card description'
            value={description}
            onChange={(e) => setDescription(e.target.value)}
          />
          <Button
            type='submit'
            variant='contained'
            color='primary'
            disabled={
              title === card.title &&
              (description === card.description ||
                (description === '' && !card.description))
            }
            className={classes.button}
          >
            Save All Changes
          </Button>
        </form>
        <div className={classes.modalSection}>
          <CardMembers card={card} />
          <div>
            <h3 className={classes.labelTitle}>Label</h3>
            <GithubPicker
              className={classes.colorPicker}
              onChange={async (color) => dispatch(editCard(cardId, { label: color.hex }))}
            />
            <Button
              className={classes.noLabel}
              variant='outlined'
              onClick={async () => dispatch(editCard(cardId, { label: 'none' }))}
            >
              No Label
            </Button>
          </div>
        </div>
        <Checklist card={card} />
        <div className={classes.modalSection}>
          <MoveCard cardId={cardId} setOpen={setOpen} thisList={list} />
          <div className={classes.modalBottomRight}>
            <Button
              variant='contained'
              className={classes.archiveButton}
              onClick={onArchiveCard}
            >
              Archive Card
            </Button>
            <DeleteCard cardId={cardId} setOpen={setOpen} list={list} />
          </div>
        </div>
      </div>
    </Modal>
  );
}
Example #22
Source File: AddQuestionModal.js    From quizdom with MIT License 4 votes vote down vote up
export default function AddQuestionModal({
	type = 'add',
	title = '',
	opType = 'radio',
	opArray,
	index = -1,
	addQuestionHandle,
}) {
	const classes = useStyles()
	const [open, setOpen] = React.useState(false)
	const [optionType, setOptionType] = useState('radio')
	const [optionsArray, setOptionsArray] = useState([])
	const [editedOption, setEditedOption] = useState(null)
	const [editOpIndex, setEditOpIndex] = useState(-1)
	const [titleField, setTitleField] = useState('')
	const optionsRef = useRef(null)
	const checkBoxRef = useRef(null)

	useEffect(() => {
		if (open) {
			setTitleField(title)
			setOptionType(opType)
			if (opArray) setOptionsArray(opArray)
		} else {
			setTitleField('')
			setOptionsArray([])
			setOptionType('radio')
		}
	}, [open, title, opType, opArray])
	const handleOpen = () => {
		setOpen(true)
	}

	const handleClose = () => {
		setOpen(false)
	}
	const addQuestionCallBack = () => {
		const tempArr = [...optionsArray]
		if (optionsRef.current.value.length !== 0) {
			// For radio options, set all other options incorrect
			if (optionType === 'radio' && checkBoxRef.current.checked)
				tempArr.forEach((op) => (op.isCorrect = false))

			tempArr.push({
				text: optionsRef.current.value,
				isCorrect: checkBoxRef.current.checked,
			})
		}
		// Error Handling
		if (!titleField.length && optionsArray.length < 2) {
			alert('Please add Question and atleast 2 options.')
			return
		} else if (!titleField.length) {
			alert('Please add Question.')
			return
		} else if (optionsArray.length < 2) {
			alert('Number of Options must be greater than 1.')
			return
		}
		const correctOp = optionsArray.filter((op) => op.isCorrect)
		if (correctOp.length < 1) {
			alert('No correct option was selected.')
			return
		}
		if (index !== -1) addQuestionHandle(titleField, optionType, tempArr, index)
		else addQuestionHandle(titleField, optionType, tempArr)

		setOpen(false)
	}

	const addOption = () => {
		if (optionsRef.current.value.length === 0) return

		const arr = [...optionsArray]
		if (
			optionsArray.findIndex((op) => op.text === optionsRef.current.value) !==
			-1
		) {
			alert('Option already exists.')
			return
		}
		if (optionType === 'radio' && checkBoxRef.current.checked)
			// For radio options, set all other options incorrect
			arr.forEach((op) => (op.isCorrect = false))

		arr.push({
			text: optionsRef.current.value,
			isCorrect: checkBoxRef.current.checked,
		})
		optionsRef.current.value = ''
		checkBoxRef.current.checked = false
		setOptionsArray(arr)
	}
	const handleTypeChange = (e) => setOptionType(e.target.value)

	const deleteHandler = (ind) => {
		const temp = [...optionsArray]
		temp.splice(ind, 1)
		setOptionsArray(temp)
		setEditOpIndex(-1)
	}

	const handleEdit = (ind) => {
		if (editOpIndex === -1) {
			setEditOpIndex(ind)
			setEditedOption(optionsArray[ind].text)
		}
	}

	const saveEdited = () => {
		const temp = [...optionsArray]
		temp[editOpIndex].text = editedOption
		setOptionsArray(temp)
		setEditOpIndex(-1)
	}

	return (
		<div className={classes.root}>
			{type === 'add' ? (
				<button className='button' onClick={handleOpen}>
					Add Question
				</button>
			) : (
				<IconButton onClick={handleOpen}>
					<EditRounded />
				</IconButton>
			)}
			<Modal
				aria-labelledby='transition-modal-title'
				aria-describedby='transition-modal-description'
				className={classes.modal}
				open={open}
				disableEnforceFocus={true}
			>
				<div className={classes.paper}>
					<div className='questionCard'>
						<div id='title'>Question:</div>
						<input
							type='text'
							autoFocus
							value={titleField}
							onChange={(e) => setTitleField(e.target.value)}
							className='input-text question'
							placeholder='Type Question Here'
						/>
						<select
							id='select'
							placeholder='Select'
							onChange={handleTypeChange}
						>
							<option className='selectOp' value='radio'>
								Single Answer
							</option>
							<option className='selectOp' value='check'>
								Multiple Answers
							</option>
						</select>

						<div className='option-div'>
							<div className='options' id='one-op'>
								{optionsArray.map((option, ind) => (
									<div className='option' key={ind}>
										<input
											type={optionType === 'radio' ? 'radio' : 'checkbox'}
											disabled={true}
											className='radio-in'
											name='option'
											checked={option.isCorrect}
										/>
										{editOpIndex === ind ? (
											<input
												value={editedOption}
												onChange={(e) => setEditedOption(e.target.value)}
											/>
										) : (
											<div className='add-op'>{option.text}</div>
										)}
										{editOpIndex === ind ? (
											<Icon className='save-icon' onClick={() => saveEdited()}>
												<SaveRounded />
											</Icon>
										) : (
											<Icon
												className='edit-icon'
												onClick={() => handleEdit(ind)}
											>
												<EditRounded />
											</Icon>
										)}
										<Icon
											className='delete-icon'
											onClick={() => {
												deleteHandler(ind)
											}}
										>
											<DeleteRounded />
										</Icon>
									</div>
								))}
							</div>
						</div>

						<div className='add-op'>
							<div>
								<input
									type={optionType === 'radio' ? 'radio' : 'checkbox'}
									ref={checkBoxRef}
									className='radio-in'
									name='option'
								/>
								<input
									type='text'
									ref={optionsRef}
									className='input-text op-text'
									placeholder={`Option ${optionsArray.length + 1}`}
								/>
							</div>
							<input
								type='submit'
								className='add-btn'
								value='+ Add'
								onClick={addOption}
							/>
						</div>
					</div>
					<div className={classes.buttons}>
						<button className='add-btn' onClick={handleClose}>
							Close
						</button>
						<button
							// disabled={!(optionsArray.length && titleField.length)}
							className='button'
							color='secondary'
							variant='contained'
							onClick={addQuestionCallBack}
						>
							{type === 'add' ? 'Add ' : 'Edit '}
							Question
						</button>
					</div>
				</div>
			</Modal>
		</div>
	)
}
Example #23
Source File: BlockUser.js    From medha-STPC with GNU Affero General Public License v3.0 4 votes vote down vote up
BlockUser = props => {
  const [open, setOpen] = React.useState(false);
  const [formState, setFormState] = useState({
    isDataBlockUnblock: false,
    isValid: false,
    stateCounter: 0,
    values: {}
  });

  const handleCloseModal = (message = "") => {
    setOpen(false);
    /** This event handles the scenario when the pop up is closed just by clicking outside the popup 
    to ensure that only string value is passed to message variable */
    if (typeof message !== "string") {
      message = "";
    }
    setFormState(formState => ({
      ...formState,
      values: {},
      isDataBlockUnblock: false,
      isValid: false,
      stateCounter: 0
    }));
    if (formState.isDataBlockUnblock) {
      props.closeModal(true, message);
    } else {
      props.closeModal(false, message);
    }
  };

  const handleSubmit = event => {
    setOpen(true);
    /** CALL Put FUNCTION */
    blockUser();
    props.clearSelectedRow(true);
    event.preventDefault();
  };
  const blockUser = () => {
    var body;
    if (props.isUnBlocked || props.isMultiUnblock) {
      body = {
        blocked: false
      };
    }
    if (props.isBlocked || props.isMulBlocked) {
      body = {
        blocked: true
      };
    }

    if (props.isMulBlocked || props.isMultiUnblock) {
      let MultiBlockUnblockUrl;
      if (props.isMulBlocked) {
        MultiBlockUnblockUrl = USER_URL + strapiConstants.STRAPI_BLOCK_URL;
      } else if (props.isMultiUnblock) {
        MultiBlockUnblockUrl = USER_URL + strapiConstants.STRAPI_UNBLOCK_URL;
      }
      let MultiBlockUnblockId = {
        ids: props.id
      };
      serviceProviders
        .serviceProviderForPostRequest(
          MultiBlockUnblockUrl,
          MultiBlockUnblockId
        )
        .then(res => {
          setFormState(formState => ({
            ...formState,
            isValid: true
          }));
          formState.isDataBlockUnblock = true;
          if (props.isMultiUnblock) {
            handleCloseModal("Users has been unblocked");
          } else {
            handleCloseModal("Users has been blocked");
          }
        })
        .catch(error => {
          console.log("error");
          formState.isDataBlockUnblock = false;
          if (props.isMultiUnblock) {
            handleCloseModal("Error unblocking selected Users");
          } else {
            handleCloseModal("Error blocking selected Users");
          }
        });
    } else {
      let BLOCK_URL;
      if (props.dataToBlockUnblock.isUserBlock === true) {
        BLOCK_URL = USER_URL + strapiConstants.STRAPI_BLOCK_URL;
      } else if (props.dataToBlockUnblock.isUserBlock === false) {
        BLOCK_URL = USER_URL + strapiConstants.STRAPI_UNBLOCK_URL;
      }

      let BLOCKUNBLOCKID = {
        ids: parseInt(props.id)
      };
      serviceProviders
        .serviceProviderForPostRequest(BLOCK_URL, BLOCKUNBLOCKID)
        .then(res => {
          formState.isDataBlockUnblock = true;
          if (props.dataToBlockUnblock["isUserBlock"]) {
            handleCloseModal(
              "User " + props.dataToBlockUnblock["name"] + " has been blocked"
            );
          } else {
            handleCloseModal(
              "User " + props.dataToBlockUnblock["name"] + " has been unblocked"
            );
          }
        })
        .catch(error => {
          console.log("error", error);
          formState.isDataBlockUnblock = false;
          handleCloseModal("user unblock successfully");
        });
    }
  };

  const handleBlock = async event => {
    props.clearSelectedRow(true);
    props.closeModal();
  };

  const classes = useStyles();
  return (
    <Modal
      aria-labelledby="transition-modal-title"
      aria-describedby="transition-modal-description"
      className={classes.modal}
      open={props.getModel}
      onClose={handleCloseModal}
      closeAfterTransition
      BackdropComponent={Backdrop}
      BackdropProps={{
        timeout: 500
      }}
    >
      <Fade in={props.getModel}>
        <div className={classes.paper}>
          <div className={classes.blockpanel}>
            <Typography variant={"h2"} className={classes.textMargin}>
              {props.isUnBlocked || props.isMultiUnblock ? "Unblock" : null}
              {props.isBlocked || props.isMulBlocked ? "Block" : null}
            </Typography>
            <div className={classes.crossbtn}>
              <IconButton
                aria-label="close"
                className={classes.closeButton}
                onClick={props.modalClose}
              >
                <CloseIcon />
              </IconButton>
            </div>
          </div>
          <div className={classes.edit_dialog}>
            <Grid item xs={12}>
              <Grid
                container
                spacing={2}
                alignItems="center"
                justifyContent="center"
              >
                <Grid item lg className={classes.deletemessage}>
                  {props.isUnBlocked
                    ? "Are you sure you want to unblock user " +
                      props.dataToBlockUserName
                    : null}
                  {props.isMultiUnblock
                    ? "Are you sure you want to unblock the selected users "
                    : null}
                  {props.isBlocked
                    ? "Are you sure you want to block user " +
                      props.dataToBlockUserName
                    : null}
                  {props.isMulBlocked
                    ? "Are you sure you want to block the selected users "
                    : null}
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12}>
              <Grid
                container
                direction="row"
                justify="flex-end"
                alignItems="center"
                spacing={2}
              >
                <Grid item>
                  <YellowButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleSubmit}
                  >
                    OK
                  </YellowButton>
                </Grid>
                <Grid item>
                  <GrayButton
                    type="submit"
                    color="primary"
                    variant="contained"
                    onClick={handleBlock}
                  >
                    Close
                  </GrayButton>
                </Grid>
              </Grid>
            </Grid>
          </div>
          <Backdrop className={classes.backdrop} open={open}>
            <CircularProgress color="inherit" />
          </Backdrop>
        </div>
      </Fade>
    </Modal>
  );
}
Example #24
Source File: Dashboard.jsx    From soundly with MIT License 4 votes vote down vote up
Dashboard = () => {
  const { data, error, isLoading } = useMoralisQuery("GameScore");
  const [open, setOpen] = useState(false);
  const [score, setScore] = useState(0);
  const [userBal, setUserBal] = useState(null)
  const handleOpen = () => {
    setOpen(true);
  };
  const handleClose = () => {
    setOpen(false);
  };

  const { user } = useMoralis();
  let num = 0;
  // const bob = sf.user({ address: user.get("ethAddress"), token: daix.address });
 

  const musicStat = async () => {
    console.log('checking')
        const query = new Moralis.Query("Music");
        // query.limit(1);
         query.equalTo('artistAddress', user.get("ethAddress"));
        
        const results = await query.find();
        // alert("Successfully retrieved " + results.length + " scores.");
        console.log("these are the results", results);
        // Do something with the returned Moralis.Object values
        for (let i = 0; i < results.length; i++) {
            const object = results[i];
            // console.log("details", await query.get(object.attributes.played))
          num = num + object.attributes.played;
            // console.log(object.attributes.played);
        alert(object.id + ' - ' + object.get('name') );
        }
    setScore(num)
  }

  const getBalance = async () => {
    await sf.initialize();
    // const superUser = sf.user({
    //   address: user.get("ethAddress"),
    //   token: sf.tokens.fDAIx.address
    // });
    const userBal = (await sf.cfa.getNetFlow({ superToken: sf.tokens.fDAIx.address, account: user.get("ethAddress") })).toString();
    setUserBal(userBal);
  }
  useEffect(() => {
    console.log('checking in effect')
    musicStat();
    getBalance();
    
  },[])


  // useEffect(() => {
  //   getMusic();
  // });
  
  return (
    <Container>
      {console.log('insode rhe component')}
      <Grid container spacing={6}>
        <Grid item xs={3}>
          <button onClick={musicStat}>Check stat</button>
          <h2>Analytics</h2>
          <div className={"data-box"}>
            <h4 className={"data-value"}>{score}</h4>
            <p className={"data-description"}>Followers</p>
          </div>
          <div className={"data-box"}>
            <h4 className={"data-value"}>1M</h4>
            <p className={"data-description"}>Streams</p>
          </div>
          <div className={"data-box"}>
            <h4 className={"data-value"}>4 hours</h4>
            <p className={"data-description"}>Playtime</p>
          </div>
        </Grid>
        <Grid item xs={9}>
          <h2>Overview</h2>
          <div className="data-box-large">
            <div className="overview">
                <h4>
                    Your earnings
                </h4>
                <h2>
                    {userBal}<span>Dai</span>
                </h2>
                <p>Update your payment method</p>

            </div>
            <div className="image-wrapper">
              <img src="./img/currency.png" alt="currency image" />
            </div>
            <Button onClick={handleOpen} className={"dark-btn"}>Withdraw Earning</Button>
            <Modal
              open={open}
              onClose={handleClose}
              aria-labelledby="withdraw-box"
              aria-describedby="modal-modal-description"
            >
              <div id={"withdraw-box"}>
                <h4>Withdrawal</h4>
                <TextField
                  id="amount"
                  label="Amount"
                  defaultValue="Hello World"
                                  type="number"
                                  variant="standard"
                  InputLabelProps={{
                    shrink: true,
                  }}
                />
                <Button
                  onClick={() => {
                    alert("clicked");
                  }}
                  variant="contained"
                >
                  Withdraw
                </Button>
              </div>
            </Modal>
                  </div>
                  <div className="chart">
                      <Line data={data}
	options={options} />
                  </div>
        </Grid>
      </Grid>
    </Container>
  );
}
Example #25
Source File: edit-product-form.js    From horondi_admin with MIT License 4 votes vote down vote up
EditProductForm = ({
  open,
  onCloseHandler,
  selectedItem,
  setFieldValue,
  setSizeItems,
  items
}) => {
  const { materialUiConstants } = config;
  const { productLabels } = configs;
  const classes = useStyles();
  const dispatch = useDispatch();

  const [size, setSize] = useState({ _id: '', name: '', price: {} });
  const [quantity, setQuantity] = useState('');

  useEffect(() => {
    if (selectedItem) {
      setQuantity(selectedItem.quantity);
      setSize(selectedItem.options.size);
    }
  }, [selectedItem]);

  const { sizes } = useSelector(({ Products }) => ({
    sizes: Products.selectedProduct.sizes
  }));

  useEffect(() => {
    selectedItem && dispatch(getProduct(selectedItem.product._id));
  }, [selectedItem]);

  const selectHandler = (e) => {
    setSize({
      _id: e.target.value,
      name: sizes.filter(({ size: sz }) => sz._id === e.target.value)[0].size
        .name,
      price: sizes.filter(({ size: sz }) => sz._id === e.target.value)[0].price
    });
  };

  const sizeItems = setSizeItems(sizes);

  const confirmHandler = () => {
    const index = items.findIndex(
      (item) => item.product._id === selectedItem.product._id
    );
    const newValue = { ...items[index], ...items[index].options };
    newValue.options.size._id = size._id;
    newValue.options.size.price = size.price;
    newValue.options.size.name = size.name;
    newValue.quantity = quantity;
    setFieldValue(inputName.itemsName, [
      ...items.slice(0, index),
      newValue,
      ...items.slice(index + 1)
    ]);
    onCloseHandler();
  };
  return (
    <Modal open={open} onClose={onCloseHandler}>
      <div className={classes.selectedProduct}>
        <h2 className={classes.productHeading}>
          {selectedItem?.product && selectedItem.product.name[0].value}
        </h2>
        <div className={classes.quantity}>
          {productLabels.quantity}
          <Button
            onClick={() => setQuantity((prev) => prev - 1)}
            disabled={quantity <= 1}
          >
            <RemoveIcon />
          </Button>
          <h3>{quantity}</h3>
          <Button onClick={() => setQuantity((prev) => prev + 1)}>
            <AddIcon />
          </Button>
        </div>
        <div>
          {productLabels.size}
          <Select value={size._id} onChange={selectHandler}>
            {sizeItems}
          </Select>
        </div>
        <br />
        <Button
          variant={materialUiConstants.contained}
          color={materialUiConstants.primary}
          disabled={
            size._id === selectedItem?.options.size._id &&
            quantity === selectedItem?.quantity
          }
          onClick={confirmHandler}
        >
          {productLabels.saveProduct}
        </Button>
      </div>
    </Modal>
  );
}
Example #26
Source File: Content.js    From hacktoberfest-participants with MIT License 4 votes vote down vote up
function Content(props) {
  const { edges } = props.data.allContributorsJson;
  const participantsPerPage = 6;
  const classes = useStyles();
  const [modal, setModal] = React.useState(false);
  const [filteredParticipants, setFilteredParticipants] = React.useState(edges);
  const [searchText, setSearchText] = React.useState('');
  const [firstParticipantIndex, setFirstParticipantIndex] = React.useState(0);
  const [participantsCount, setParticipantsCount] = React.useState(
    edges.length
  );
  const handleSearch = ({ target: { value } }) => {
    setSearchText(value);
    setFirstParticipantIndex(0);
  };

  React.useEffect(() => {
    if (searchText) {
      const caseFreeSearchText = searchText.trim().toLowerCase();
      if (!edges || !edges.length) return;

      const filteredResult = edges.filter(({ node: { name, github } }) => {
        return (
          name.toLowerCase().includes(caseFreeSearchText) ||
          getGithubUsernameFromURL(github).includes(caseFreeSearchText)
        );
      });
      setParticipantsCount(filteredResult.length);
      
      setFilteredParticipants(
        filteredResult.slice(
          firstParticipantIndex,
          firstParticipantIndex + participantsPerPage
        )
      );
    } else {
      setParticipantsCount(
        edges.length
      );
      setFilteredParticipants(
        edges.slice(
          firstParticipantIndex,
          firstParticipantIndex + participantsPerPage
        )
      );
    }
  }, [searchText, firstParticipantIndex, participantsCount]);

  const [id, setID] = React.useState(null);
  return (
    <main>
      <div className={classes.heroContent}>
        <Container maxWidth='sm'>
          <Typography
            component='h1'
            variant='h3'
            align='center'
            color='inherit'
            gutterBottom
          >
            Are you participating?{' '}
            <span role='img' aria-label='thinking'>
              ?
            </span>
          </Typography>
          <Typography
            variant='h5'
            align='center'
            color='textSecondary'
            paragraph
          >
            <u>
              <a
                href='https://hacktoberfest.digitalocean.com/'
                style={{ textDecoration: 'none', color: 'inherit' }}
              >
                Hacktoberfest
              </a>
            </u>{' '}
            is the time to come together and make the open-source world a better
            place. ? Go raise a PR and add yourself in the list.
          </Typography>
          <div className={classes.heroButtons}>
            <Grid container spacing={2} justify='center'>
              <Grid item>
                <AwesomeButtonSocial
                  className={classes.btn}
                  type='github'
                  target='_blank'
                  href='https://github.com/iamdarshshah/hacktoberfest-participants#steps-to-add-yourself-in-the-list'
                >
                  Create a Pull Request
                </AwesomeButtonSocial>
              </Grid>
            </Grid>
          </div>
        </Container>
        <Container maxWidth='md'>
          <Grid container spacing={1} justify='center'>
            <Grid item xs={12} sm={8} md={5}>
              <SearchTextField
                startAdornment={
                  <InputAdornment position='start'>
                    <SearchIcon />
                  </InputAdornment>
                }
                onChange={handleSearch}
                InputLabelProps={{
                  shrink: true,
                }}
                style={{ marginTop: 40 }}
                fullWidth
                margin='normal'
                variant='outlined'
                placeholder='Search by name or Github username'
                id='input-with-icon-grid'
                color='secondary'
              />
            </Grid>
          </Grid>
        </Container>
      </div>
      <Container className={classes.cardGrid} maxWidth='md'>
        <Grid container spacing={4}>
          {Boolean(filteredParticipants.length) &&
            filteredParticipants.map((edge, index) => {
              return (
                <Grid key={index} item xs={12} sm={6} md={4}>
                  <Card
                    className={classes.card}
                    onClick={() => {
                      setModal(true);
                      const githubID = edge.node.github.split('.com/')[1];
                      setID(githubID);
                    }}
                  >
                    <CardContent className={classes.cardContent}>
                      <Typography
                        gutterBottom
                        variant='h5'
                        align='center'
                        component='h2'
                      >
                        <b>
                          <u>
                            <i>{`${edge.node.name}`}</i>
                          </u>
                        </b>
                      </Typography>
                      <Typography />
                      <Typography
                        gutterBottom
                        variant='h6'
                        align='center'
                        component='h2'
                      >{`${edge.node.desc}`}</Typography>
                    </CardContent>
                    <Divider />
                    <CardContent>
                      <Typography className={classes.extraMargin}>
                        {edge.node.github ? (
                          <Link
                            className={classes.iconCls}
                            href={edge.node.github}
                            component='a'
                            target='_blank'
                          >
                            <GitHubIcon />
                          </Link>
                        ) : null}
                        {edge.node.twitter ? (
                          <Link
                            className={classes.iconCls}
                            href={edge.node.twitter}
                            component='a'
                            target='_blank'
                          >
                            <TwitterIcon />
                          </Link>
                        ) : null}
                        {edge.node.linkedin ? (
                          <Link
                            className={classes.iconCls}
                            href={edge.node.linkedin}
                            component='a'
                            target='_blank'
                          >
                            <LinkedInIcon />
                          </Link>
                        ) : null}
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>
              );
            })}
          {!Boolean(filteredParticipants.length) && (
            <Grid item xs={12}>
              <Typography
                component='div'
                variant='h5'
                align='center'
                color='inherit'
                gutterBottom
              >
                {' '}
                <span role='img' aria-label='user not found'>
                  ?
                </span>{' '}
                No participant found
              </Typography>
            </Grid>
          )}
          <Modal
            disableEnforceFocus
            disableAutoFocus
            closeAfterTransition
            open={modal}
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
            }}
            onClose={() => setModal(false)}
          >
            <div className={classes.modalContainer}>
              <Fade in={modal}>
                <Profile id={id} />
              </Fade>
            </div>
          </Modal>
        </Grid>
        <Pagination
          onPrev={() => {
            setFirstParticipantIndex((prev) =>
              prev - participantsPerPage >= 0 ? prev - participantsPerPage : 0
            );
          }}
          onNext={() => {
            setFirstParticipantIndex((prev) => {
              return prev + participantsPerPage >= edges.length
                ? prev
                : prev + participantsPerPage;
            });
          }}
          actualPage={Math.ceil(
            (firstParticipantIndex + 1) / participantsPerPage
          )}
          pagesCount={Math.ceil(participantsCount / participantsPerPage)}
        ></Pagination>
      </Container>
    </main>
  );
}
Example #27
Source File: AppBar.js    From floor-plan-lab with MIT License 4 votes vote down vote up
function AppBar() {
  const dispatch = useDispatch();
  const classes = useStyles();
  const [textboxAnchor, setTextboxAnchor] = React.useState(null);
  const [fileAnchor, setFileAnchor] = React.useState(null);
  const [objectModalOpen, setObjectModalOpen] = React.useState(false);
  const [warningModalOpen, setWarningModalOpen] = React.useState(false);
  const [tutorialModalOpen, setTutorialModalOpen] = React.useState(true);
  const [curTab, setCurTab] = React.useState(0);
  const [tutorialTab, setTutorialTab] = React.useState(1);
  const [toolbarTab, setToolbarTab] = React.useState(0);


  const handleClickTextbox = (event) => {
    setTextboxAnchor(event.currentTarget);
  };

  const handleClickFile = (event) => {
    setFileAnchor(event.currentTarget);
  };

  const handleCloseTextbox = () => {
    setTextboxAnchor(null);
  };

  const handleCloseFile = () => {
    setFileAnchor(null);
  };

  const insertLabel = () => {
    dispatch(addText('label'));
    handleCloseTextbox();
  }

  const newFile = () => {
    dispatch(setNewFile());
    handleWarningModalClose();
  }

  const handleObjectModalClose = () => {
    setObjectModalOpen(false);
  };

  const handleTutorialModalClose = () => {
    setTutorialModalOpen(false);
  };

  const handleWarningModalClose = () => {
    setWarningModalOpen(false);
    handleCloseFile();
  };

  const openObjectModal = () => {
    dispatch(setTool('POINTER'));
    dispatch(setAnchor(null));
    dispatch(setCurShape(null));
    dispatch(updateEdges([]));
    dispatch(updateSelected([]));
    setObjectModalOpen(true);
  }

  const openTutorialModal = () => {
    setTutorialTab(1);
    setTutorialModalOpen(true);
  }

  const openWarningModal = () => {
    setWarningModalOpen(true);
  }

  const changeTab = (event, newValue) => {
    setCurTab(newValue);
  };

  const placeObject = (objectType) => {
    dispatch(addObject(objectType));
  }

  const getImgHeight = (objectType) => {
    const objectHeight = getObjectSize(objectType).h;
    return Math.round((objectHeight / 36) * 80);
  }

  const handleChangeToolbarTab = (event, newValue) => {
    setToolbarTab(newValue);
  };

  /**
   * Calculates the image x & y offsets and width & height
   */
  const calImgCrop = (state) => {
    const padding = 17 * 2;
    let xOffset = 999999999;
    let yOffset = 999999999;
    let maxX = 0;
    let maxY = 0;
    state.objects.forEach(object => {
      if (object.position.x < xOffset) { xOffset = object.position.x; }
      if (object.position.x > maxX) { maxX = object.position.x; }
      if (object.position.y < yOffset) { yOffset = object.position.y; }
      if (object.position.y > maxY) { maxY = object.position.y; }
    });
    state.text.forEach(textBox => {
      if (textBox.position.x < xOffset) { xOffset = textBox.position.x; }
      if (textBox.position.x > maxX) { maxX = textBox.position.x; }
      if (textBox.position.y < yOffset) { yOffset = textBox.position.y; }
      if (textBox.position.y > maxY) { maxY = textBox.position.y; }
    });
    for (let row = 0; row < state.walls.length; row++) {
      for (let col = 0; col < state.walls[0].length; col++) {
        // check for a wall
        if (state.walls[row][col] === true) {
          // calc x & y offsets
          const x = col * (boxSize + 1);
          const y = row * (boxSize + 1);
          if (x < xOffset) { xOffset = x; }
          if (x + (boxSize + 1) > maxX) { maxX = x + (boxSize + 1); }
          if (y < yOffset) { yOffset = y; }
          if (y + (boxSize + 1) > maxY) { maxY = y + (boxSize + 1); }
        }
      }
    }
    return {
      xOffset: Math.max(xOffset - padding, 0) + 54,
      yOffset: Math.max(yOffset - padding, 0) + 64,
      width: (maxX - xOffset) + padding * 2,
      height: (maxY - yOffset) + padding * 2
    }
  }

  const saveFile = () => {
    const curState = getState().sheet;
    const cropData = calImgCrop(curState);
    // Create preview image
    html2canvas(document.querySelector("#grid-container"), {
      x: cropData.xOffset,
      y: cropData.yOffset,
      width: cropData.width,
      height: cropData.height,
    }).then(canvas => {
      document.body.appendChild(canvas)
    });
    // Save file state
    const state = {
      scale: curState.scale,
      text: curState.text,
      objects: curState.objects,
      walls: curState.walls
    };
    const compressedJSON = LZUTF8.compress(JSON.stringify(state));
    dispatch(loadFile(
      JSON.parse(LZUTF8.decompress(compressedJSON))
    ));
  }

  return (
    <div>
      <Grid container className={classes.appBarContainer}>

        <Grid item>
          <img src={logo} style={{ height: 38, paddingRight: 18, paddingLeft: 4, paddingTop: 10 }} />
        </Grid>

        <Grid item>
          <Grid container>
            <Grid item>
              <Typography variant='h6' style={{ fontWeight: 700, paddingLeft: 4, fontFamily: "'Mulish', sans-serif" }}>
                Floor Plan Lab
              </Typography>
            </Grid>

            <Grid item xs style={{ paddingTop: 2 }}>
              <Typography variant='caption' style={{ fontSize: 10, paddingLeft: 8, color: '#bcd0e0' }}>
                BETA
              </Typography>
            </Grid>

            <Grid item xs={12}>
              <Grid container>
                <Grid item>
                  <Button size='small' className={classes.menuButton} onClick={handleClickFile}>
                    File
                  </Button>
                </Grid>

                <Grid item>
                  <Button size='small' className={classes.menuButton} onClick={handleClickTextbox}>
                    Place Text
                  </Button>
                </Grid>

                <Grid item>
                  <Button size='small' className={classes.menuButton} onClick={openObjectModal}>
                    Place Object
                  </Button>
                </Grid>

              </Grid>
            </Grid>
          </Grid>
        </Grid>

        <Grid item xs>
          <div className={classes.justifyRight}>
            <ButtonGroup variant="contained" color='primary'>
              <Button className={classes.button} onClick={openTutorialModal}>
                Tutorial
            </Button>
              <a href='https://github.com/dcarubia/floor-plan-lab'>
                <Button className={classes.button}>
                  View Source
                </Button>
              </a>

            </ButtonGroup>

          </div>
        </Grid>
      </Grid>

      <Menu
        anchorEl={textboxAnchor}
        getContentAnchorEl={null}
        anchorOrigin={{ vertical: "bottom" }}
        transformOrigin={{ vertical: "top" }}
        keepMounted
        open={Boolean(textboxAnchor)}
        onClose={handleCloseTextbox}
      >
        <Typography variant='overline' style={{ paddingLeft: 16 }}>Text Style:</Typography>
        <MenuItem onClick={insertLabel} className={classes.menuItem}>Label</MenuItem>
      </Menu>

      <Menu
        anchorEl={fileAnchor}
        getContentAnchorEl={null}
        anchorOrigin={{ vertical: "bottom" }}
        transformOrigin={{ vertical: "top" }}
        keepMounted
        open={Boolean(fileAnchor)}
        onClose={handleCloseFile}
      >
        <MenuItem onClick={saveFile} className={classes.menuItem}>Save</MenuItem>
        <Divider />
        <MenuItem onClick={openWarningModal} className={classes.menuItem}>New</MenuItem>
        <MenuItem className={classes.menuItem}>Open</MenuItem>
      </Menu>

      <Modal
        open={objectModalOpen}
        onClose={handleObjectModalClose}
        aria-labelledby="place-object"
      >
        <Paper className={classes.paper}>
          <Grid container>
            <Grid item style={{ borderRight: '1px solid #d5d5d5', height: 680 }}>
              <Tabs
                orientation='vertical'
                value={curTab}
                onChange={changeTab}
                indicatorColor='primary'
                textColor='primary'
              >
                <Tab label="Doors" />
                <Tab label="Windows" />
                <Tab label="Kitchen" />
                <Tab label="Bathroom" />
                <Tab label="Living Room" />
                <Tab label="Dining Room" />
                <Tab label="Bedroom" />
                <Tab label="Laundry" />
              </Tabs>
            </Grid>

            <Grid item xs>
              {curTab === 0 ? // DOORS
                <div className={classes.modalContent}>
                  <Grid container spacing={1} >
                    {
                      objects.doors.map(object =>
                        <Grid item xs={6}>
                          <div className={classes.imageContainer} onClick={() => placeObject(object.id)}>
                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 80 }}>
                              <img src={object.file} className={classes.image} style={{ height: getImgHeight(object.id) }} />
                            </div>
                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                              <Typography variant='body2'>{object.label}</Typography>
                            </div>

                          </div>
                        </Grid>
                      )
                    }
                  </Grid>
                </div>

                : curTab === 1 ? // WINDOWS
                  <div className={classes.modalContent}>
                    <Grid container spacing={1} >
                      {
                        objects.windows.map(object =>
                          <Grid item xs={6}>
                            <div className={classes.imageContainer} onClick={() => placeObject(object.id)}>
                              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 80 }}>
                                <img src={object.file} className={classes.image} style={{ height: getImgHeight(object.id) }} />
                              </div>
                              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                <Typography variant='body2'>{object.label}</Typography>
                              </div>

                            </div>
                          </Grid>
                        )
                      }
                    </Grid>
                  </div>

                  : curTab === 2 ? // KITCHEN
                    <div className={classes.modalContent}>
                      <Grid container spacing={1} >
                        {
                          objects.kitchen.map(object =>
                            <Grid item xs={6}>
                              <div className={classes.imageContainer} onClick={() => placeObject(object.id)}>
                                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 80 }}>
                                  <img src={object.file} className={classes.image} style={{ height: getImgHeight(object.id) }} />
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                  <Typography variant='body2'>{object.label}</Typography>
                                </div>

                              </div>
                            </Grid>
                          )
                        }
                      </Grid>
                    </div>

                    : curTab === 3 ? // BATHROOM
                      <div className={classes.modalContent}>
                        <Grid container spacing={1} >
                          {
                            objects.bathroom.map(object =>
                              <Grid item xs={6}>
                                <div className={classes.imageContainer} onClick={() => placeObject(object.id)}>
                                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 80 }}>
                                    <img src={object.file} className={classes.image} style={{ height: getImgHeight(object.id) }} />
                                  </div>
                                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                    <Typography variant='body2'>{object.label}</Typography>
                                  </div>

                                </div>
                              </Grid>
                            )
                          }
                        </Grid>
                      </div>

                      : curTab === 4 ? // LIVING ROOM
                        <div className={classes.modalContent}>
                          <Grid container spacing={1} >
                            {
                              objects.livingRoom.map(object =>
                                <Grid item xs={6}>
                                  <div className={classes.imageContainer} onClick={() => placeObject(object.id)}>
                                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 80 }}>
                                      <img src={object.file} className={classes.image} style={{ height: getImgHeight(object.id) }} />
                                    </div>
                                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                      <Typography variant='body2'>{object.label}</Typography>
                                    </div>

                                  </div>
                                </Grid>
                              )
                            }
                          </Grid>
                        </div>

                        : curTab === 5 ? // DINING ROOM
                          <div className={classes.modalContent}>
                            <Grid container spacing={1} >
                              {
                                objects.diningRoom.map(object =>
                                  <Grid item xs={6}>
                                    <div className={classes.imageContainer} onClick={() => placeObject(object.id)}>
                                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 80 }}>
                                        <img src={object.file} className={classes.image} style={{ height: getImgHeight(object.id) }} />
                                      </div>
                                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                        <Typography variant='body2'>{object.label}</Typography>
                                      </div>

                                    </div>
                                  </Grid>
                                )
                              }
                            </Grid>
                          </div>

                          : curTab === 6 ? // BEDROOM
                            <div className={classes.modalContent}>
                              <Grid container spacing={1} >
                                {
                                  objects.bedroom.map(object =>
                                    <Grid item xs={6}>
                                      <div className={classes.imageContainer} onClick={() => placeObject(object.id)}>
                                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 80 }}>
                                          <img src={object.file} className={classes.image} style={{ height: getImgHeight(object.id) }} />
                                        </div>
                                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                          <Typography variant='body2'>{object.label}</Typography>
                                        </div>

                                      </div>
                                    </Grid>
                                  )
                                }
                              </Grid>
                            </div>

                            : curTab === 7 ? // LAUNDRY
                              <div className={classes.modalContent}>
                                <Grid container spacing={1} >
                                  {
                                    objects.laundry.map(object =>
                                      <Grid item xs={6}>
                                        <div className={classes.imageContainer} onClick={() => placeObject(object.id)}>
                                          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 80 }}>
                                            <img src={object.file} className={classes.image} style={{ height: getImgHeight(object.id) }} />
                                          </div>
                                          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                            <Typography variant='body2'>{object.label}</Typography>
                                          </div>

                                        </div>
                                      </Grid>
                                    )
                                  }
                                </Grid>
                              </div>

                              : curTab === 8 ? // STAIRS
                                <div className={classes.modalContent}>
                                  <Grid container spacing={1} >
                                    {
                                      objects.stairs.map(object =>
                                        <Grid item xs={6}>
                                          <div className={classes.imageContainer} onClick={() => placeObject(object.id)}>
                                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 80 }}>
                                              <img src={object.file} className={classes.image} style={{ height: getImgHeight(object.id) }} />
                                            </div>
                                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                              <Typography variant='body2'>{object.label}</Typography>
                                            </div>

                                          </div>
                                        </Grid>
                                      )
                                    }
                                  </Grid>
                                </div>

                                : null
              }
            </Grid>
          </Grid>
        </Paper>
      </Modal>

      <Modal
        open={warningModalOpen}
        onClose={null}
        aria-labelledby="warning"
      >
        <Paper className={classes.warningPaper}>
          <div style={{ padding: 24 }}>
            <Typography variant='body1' style={{ fontWeight: 'bold' }}>Warning: Creating a new plan will override the current plan.</Typography>
          </div>

          <Grid container>
            <Grid item xs={6} style={{ padding: 8 }}>
              <Button variant='contained' color='primary' fullWidth onClick={newFile} >New Plan</Button>
            </Grid>
            <Grid item xs={6} style={{ padding: 8 }}>
              <Button variant='contained' color='default' fullWidth onClick={handleWarningModalClose}>Cancel</Button>
            </Grid>
          </Grid>

        </Paper>
      </Modal>

      <Modal
        open={tutorialModalOpen}
        onClose={null}
        aria-labelledby="tutorial"
      >
        <Paper className={classes.tutorialPaper}>
          <div style={{ padding: '32px 8px 16px 8px', minHeight: 520 }}>
            {tutorialTab === 1 ?
              <Grid container spacing={1}>
                <Grid item xs={12}>
                  <div style={{ display: 'flex', justifyContent: 'center' }}>
                    <Typography color='primary' variant='h4' style={{ fontWeight: 'bold' }}>Welcome to Floor Plan Lab!</Typography>
                  </div>
                </Grid>
                <Grid item xs={12}>
                  <div style={{ display: 'flex', justifyContent: 'center' }}>
                    <Typography variant='subtitle1' style={{ fontSize: 18, fontWeight: 'bold' }}>This tutorial will show you how to design a floorplan using the built in tools.</Typography>
                  </div>
                </Grid>

                <Grid item xs={12}>
                  <div style={{ display: 'flex', justifyContent: 'center' }}>
                    <img src={plan1} className={classes.gif}></img>
                  </div>
                </Grid>
                <Grid item xs={12}>
                  <div style={{ display: 'flex', justifyContent: 'center' }}>
                    <Typography variant='subtitle1' style={{ fontSize: 16 }} >At any point you can press "Skip Tutorial" to start designing.</Typography>
                  </div>
                </Grid>
              </Grid>
              : tutorialTab === 2 ?
                <Grid container spacing={1}>
                  <Grid item xs={12}>
                    <div style={{ display: 'flex', justifyContent: 'center' }}>
                      <Typography color='primary' variant='h4' style={{ fontWeight: 'bold' }}>Project Scale</Typography>
                    </div>
                  </Grid>
                  <Grid item xs={12}>
                    <div style={{ display: 'flex', justifyContent: 'center' }}>
                      <Typography variant='subtitle1' style={{ fontSize: 18, fontWeight: 'bold' }}>Start each project by specifying a grid scale. By default each grid line equals 1 ft.</Typography>
                    </div>
                  </Grid>

                  <Grid item xs={12}>
                    <div style={{ display: 'flex', justifyContent: 'center' }}>
                      <img src={changeScaleGif} className={classes.gif}></img>
                    </div>
                  </Grid>
                  <Grid item xs={12}>
                    <div style={{ display: 'flex', justifyContent: 'center' }}>
                      <Typography variant='subtitle1' style={{ fontSize: 16 }} >For more accurate object proportions we recommend decreaing the scale. </Typography>
                    </div>
                  </Grid>
                </Grid>
                : tutorialTab === 3 ?
                  <Grid container spacing={1}>
                    <Grid item xs={12}>
                      <div style={{ display: 'flex', justifyContent: 'center' }}>
                        <Typography color='primary' variant='h4' style={{ fontWeight: 'bold' }}>Toolbar</Typography>
                      </div>
                    </Grid>

                    <Grid item xs={12} style={{ padding: 0, marginRight: 8, marginBottom: 24, borderBottom: '1px solid #d5d5d5' }}>
                      <Tabs
                        orientation='horizontal'
                        value={toolbarTab}
                        onChange={handleChangeToolbarTab}
                        variant='fullWidth'
                        indicatorColor="primary"
                        textColor="primary"
                      >
                        <Tab icon={<span className="fas fa-mouse-pointer"></span>} label="MOVE" />
                        <Tab icon={<PhotoSizeSelectSmallIcon />} label="SELECT" />
                        <Tab icon={<LinearScaleIcon />} label="LINEAR WALL" />
                        <Tab icon={<span className="fas fa-vector-square"></span>} label="RECT WALL" />
                        <Tab icon={<span className="fas fa-pen"></span>} label="DRAW" />
                        <Tab icon={<span className="fas fa-eraser"></span>} label="ERASE" />
                      </Tabs>
                    </Grid>
                    {toolbarTab === 0 ? // MOVE
                      <>
                        <Grid item xs={5} style={{ padding: '8px 0px 0px 36px' }}>
                          <img src={moveToolGif} style={{ maxWidth: 360 }}></img>
                        </Grid>
                        <Grid item xs={7} style={{ paddingLeft: 24, paddingRight: 24 }}>
                          <Typography variant='h4'>Move Tool</Typography>
                          <Typography variant='subtitle1' style={{ fontSize: 21, margin: '0px 0px 0px 0px' }}>Position objects and labels.</Typography>
                          <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>Click and drag an object or label to move it.</Typography>
                          <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>When an object is selected, an object toolbar will appear at the top right of your screen. Use this toolbar to rotate, flip, or delete the selected object. </Typography>
                          <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>Note: Clicking an object at any time will automatically enable the move tool</Typography>
                        </Grid>
                      </>
                      : toolbarTab === 1 ? // SELECT
                        <>
                          <Grid item xs={5} style={{ padding: '8px 0px 0px 36px' }}>
                            <img src={selectToolGif} style={{ maxWidth: 360 }}></img>
                          </Grid>
                          <Grid item xs={7} style={{ paddingLeft: 24, paddingRight: 24 }}>
                            <Typography variant='h4'>Selection Tool</Typography>
                            <Typography variant='subtitle1' style={{ fontSize: 21, margin: '0px 0px 0px 0px' }}>Click and drag to select grid-squares.</Typography>
                            <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>Keyboard commands:</Typography>
                            <Typography variant='subtitle1' style={{ fontSize: 18, margin: '4px 0px 0px 0px' }}><strong>[W] - </strong>Creates a wall from the selected grid-squares</Typography>
                            <Typography variant='subtitle1' style={{ fontSize: 18, margin: '4px 0px 0px 0px' }}><strong>[BACKSPACE] - </strong>Deletes selected walls</Typography>
                            <Typography variant='subtitle1' style={{ fontSize: 18, margin: '4px 0px 0px 0px' }}><strong>[ESC] - </strong>Cancels current selection</Typography>
                            <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>Note: The selection tool has no affect on objects or labels</Typography>
                          </Grid>
                        </>
                        : toolbarTab === 2 ? // LINEAR WALL
                          <>
                            <Grid item xs={5} style={{ padding: '8px 0px 0px 36px' }}>
                              <img src={lineToolGif} style={{ maxWidth: 360 }}></img>
                            </Grid>
                            <Grid item xs={7} style={{ paddingLeft: 24, paddingRight: 24 }}>
                              <Typography variant='h4'>Linear Wall Tool</Typography>
                              <Typography variant='subtitle1' style={{ fontSize: 21, margin: '0px 0px 0px 0px' }}>Build straight walls one grid-square in width.</Typography>
                              <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>Click on a grid-square or wall to place the first anchor point, then click a different square in the same row or column to build the wall.</Typography>
                              <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>Keyboard commands:</Typography>
                              <Typography variant='subtitle1' style={{ fontSize: 18, margin: '4px 0px 0px 0px' }}><strong>[ESC] - </strong>Removes anchor point</Typography>
                              <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>Note: You can use the linear wall tool to measure distances without building a wall</Typography>
                            </Grid>
                          </>
                          : toolbarTab === 3 ? // RECTANGULAR WALL
                            <>
                              <Grid item xs={5} style={{ padding: '8px 0px 0px 36px' }}>
                                <img src={rectWallGif} style={{ maxWidth: 360 }}></img>
                              </Grid>
                              <Grid item xs={7} style={{ paddingLeft: 24, paddingRight: 24 }}>
                                <Typography variant='h4'>Rectangular Wall Tool</Typography>
                                <Typography variant='subtitle1' style={{ fontSize: 21, margin: '0px 0px 0px 0px' }}>Build a rectangular room surrounded by walls.</Typography>
                                <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>Click on a grid-square or wall to place the first anchor point, then click a different square to build the walls.</Typography>
                                <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>Keyboard commands:</Typography>
                                <Typography variant='subtitle1' style={{ fontSize: 18, margin: '4px 0px 0px 0px' }}><strong>[ESC] - </strong>Removes anchor point</Typography>
                                <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>Note: You can use the rectangular wall tool to measure dimensions and room area without building a wall</Typography>
                              </Grid>
                            </>
                            : toolbarTab === 4 ? // DRAW
                              <>
                                <Grid item xs={5} style={{ padding: '8px 0px 0px 36px' }}>
                                  <img src={drawToolGif} style={{ maxWidth: 360 }}></img>
                                </Grid>
                                <Grid item xs={7} style={{ paddingLeft: 24, paddingRight: 24 }}>
                                  <Typography variant='h4'>Draw Tool</Typography>
                                  <Typography variant='subtitle1' style={{ fontSize: 21, margin: '0px 0px 0px 0px' }}>Freely draw walls.</Typography>
                                  <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>Click and drag to convert empty grid-squares into walls.</Typography>
                                </Grid>
                              </>
                              : toolbarTab === 5 ? // ERASE
                                <>
                                  <Grid item xs={5} style={{ padding: '8px 0px 0px 36px' }}>
                                    <img src={eraseToolGif} style={{ maxWidth: 360 }}></img>
                                  </Grid>
                                  <Grid item xs={7} style={{ paddingLeft: 24, paddingRight: 24 }}>
                                    <Typography variant='h4'>Eraser Tool</Typography>
                                    <Typography variant='subtitle1' style={{ fontSize: 21, margin: '0px 0px 0px 0px' }}>Remove walls.</Typography>
                                    <Typography variant='subtitle1' style={{ fontSize: 18, margin: '24px 0px 0px 0px' }}>Click and drag to erase a wall.</Typography>
                                  </Grid>
                                </>
                                : null
                    }
                  </Grid>
                  : tutorialTab === 4 ?
                    <Grid container spacing={1}>


                      <Grid item xs={8}>
                        <Grid container spacing={1} style={{ padding: '0px 24px 0px 24px' }}>
                          <Grid item xs={12}>
                            <Typography color='primary' variant='h4' style={{ fontWeight: 'bold' }}>Place Objects</Typography>
                          </Grid>
                          <Grid item xs={12}>
                            <Typography variant='subtitle1' style={{ fontSize: 18, fontWeight: 'bold' }}>Place common floorplan symbols that scale automatically.</Typography>
                          </Grid>
                          <Grid item xs={12}>
                            <Typography variant='subtitle1' style={{ fontSize: 15 }} >In the "Place Object" menu, choose a category and click on an object to place it. When overlapping, the more recently placed object will be in the front.</Typography>
                          </Grid>
                          <Grid item xs={12}>
                            <Typography variant='subtitle1' style={{ fontSize: 15 }} >To delete an object, click on it to select the object, then click delete in the object toolbar located at the top right of your screen.</Typography>
                          </Grid>
                        </Grid>
                      </Grid>

                      <Grid item xs={4}>
                        <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
                          <img src={placeObjectGif} style={{ maxHeight: 250 }}></img>
                        </div>
                      </Grid>

                      <Grid item>
                        <div style={{ display: 'flex', justifyContent: 'flex-start', paddingLeft: 24 }}>
                          <img src={placeTextGif} style={{ maxHeight: 250 }}></img>
                        </div>
                      </Grid>
                      <Grid item xs>
                        <Grid container spacing={1} style={{ padding: '24px 24px 0px 24px' }}>
                          <Grid item xs={12}>
                            <Typography color='primary' variant='h4' style={{ fontWeight: 'bold' }}>Place Text</Typography>
                          </Grid>
                          <Grid item xs={12}>
                            <Typography variant='subtitle1' style={{ fontSize: 18, fontWeight: 'bold' }}>Place a draggable text label.</Typography>
                          </Grid>
                          <Grid item xs={12}>
                            <Typography variant='subtitle1' style={{ fontSize: 15 }} >In the "Place Text" menu, choose "Label". Type your label and press enter or click "Save". Click on the label at any time to make changes. To move the textbox, enter edit mode then click and drag on the handle at the left side of the textbox.</Typography>
                          </Grid>
                        </Grid>
                      </Grid>
                    </Grid>
                    : null
            }

          </div>

          <Grid container>
            <Grid item xs={3} style={{ padding: '0px 16px 16px 16px' }}>
              <Button variant='contained' color='default' onClick={handleTutorialModalClose}>Skip Tutorial</Button>
            </Grid>
            <Grid item xs={3}>
              <div style={{ display: 'flex', justifyContent: 'flex-end', paddingTop: 4 }}>
                <Typography variant='h6'>{tutorialTab}/4</Typography>
              </div>
            </Grid>
            <Grid item xs={6} style={{ padding: '0px 16px 16px 16px' }}>
              <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                {tutorialTab > 1 ?
                  <Button variant='contained' color='default' onClick={() => setTutorialTab(tutorialTab - 1)} style={{ marginRight: 8 }}>Back</Button>
                  : null}
                {tutorialTab < 4 ?
                  <Button variant='contained' color='primary' onClick={() => setTutorialTab(tutorialTab + 1)} >Next</Button>
                  : null}
                {tutorialTab === 4 ?
                  <Button variant='contained' color='primary' onClick={handleTutorialModalClose} >Finish</Button>
                  : null}
              </div>
            </Grid>
          </Grid>

        </Paper>
      </Modal>
    </div >
  );
}
Example #28
Source File: SetScaleModal.js    From floor-plan-lab with MIT License 4 votes vote down vote up
function SetScaleModal() {
  const classes = useStyles();
  const dispatch = useDispatch();
  const [scaleModalOpen, setScaleModalOpen] = React.useState(false);
  const [feetInput, setFeetInput] = React.useState(1);
  const [inchesInput, setInchesInput] = React.useState(0);
  const scale = useSelector(state => state.sheet.scale);

  const handleClose = () => {
    setScaleModalOpen(false);
  };

  const toggleModal = () => {
    setScaleModalOpen(!scaleModalOpen);
    setFeetInput(scale.ft);
    setInchesInput(scale.in);
  }

  const handleFeetInput = (value) => {
    setFeetInput(value);
  }

  const handleInchesInput = (value) => {
    setInchesInput(value);
  }

  const onSave = () => {
    const feet = parseInt(feetInput);
    const inches = parseInt(inchesInput);
    if (feet > 0 || inches > 0) {
      // Valid number entered
      dispatch(setScale({ ft: feet, in: inches }));
      setScaleModalOpen(false);
    } else {
      // Error
    }
  }

  return (
    <>
      <Tooltip title={<span className={classes.toolTip}>Change Scale</span>} placement='top' arrow>
        <Fab onClick={toggleModal} variant="extended" size='small' className={classes.fab} style={{ paddingLeft: 16, paddingRight: 16, }}>
          <span className="far fa-square" style={{ paddingRight: 8 }}></span>
            = {scale.ft}'{scale.in}"
          </Fab>
      </Tooltip>

      <Modal
        open={scaleModalOpen}
        onClose={handleClose}
        aria-labelledby="change-scale"
      >
        <Paper className={classes.paper}>
          <Grid container spacing={2}>
            <Grid item xs={12}>
              <Typography variant='h6'>
                Grid Scale
              </Typography>
            </Grid>



            <Grid item xs={12}>
              <Grid container>
                <Grid item>
                  <img src={boxSideLengthImg} className={classes.img} />
                </Grid>
                <Grid item>
                  <Grid container className={classes.inputContainer}>
                    <Grid item>
                      <NumericInput strict min={0} max={50} size={3} value={feetInput} onChange={(e) => handleFeetInput(e)} />
                    </Grid>
                    <Grid item xs>
                      <Typography style={{ paddingLeft: 4 }}>Feet</Typography>
                    </Grid>
                  </Grid>
                </Grid>

                <Grid item>
                  <Grid container className={classes.inputContainer}>
                    <Grid item>
                      <NumericInput strict min={0} max={11} size={3} value={inchesInput} onChange={(e) => handleInchesInput(e)} />
                    </Grid>
                    <Grid item xs>
                      <Typography style={{ paddingLeft: 4 }}>Inches</Typography>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            </Grid>

            <Grid item xs={12}>
              <Typography variant='caption' style={{ color: 'red' }}>
                Note: Changing the scale will resize objects but not walls.
              </Typography>
            </Grid>

            <Grid item xs={6}>
              <Button fullWidth variant='contained' color='primary' onClick={onSave}>
                Save
              </Button>
            </Grid>

            <Grid item xs={6}>
              <Button fullWidth variant='contained' onClick={handleClose}>
                Cancel
              </Button>
            </Grid>
          </Grid>
        </Paper>
      </Modal>
    </>
  );
}
Example #29
Source File: index.js    From Recess with MIT License 4 votes vote down vote up
function Homepage({ posts, user }) {
  const classes = useStyles();
  const history = useHistory();
  const [Id, setId] = useState("");
  const [modalExp, setModal] = useState(false);
  const [value, setValue] = useState({});
  const [isVal, setIsVal] = useState(false);
  const [modalComments, setModalComments] = useState([]);
  const [comment, setComment] = useState("");
  const [open, setOpen] = useState(!user);

  const postComment = (event) => {
    event.preventDefault();

    db.collection("posts").doc(Id).collection("comments").add({
      username: user.displayName,
      text: comment,
      timestamp: firebase.firestore.FieldValue.serverTimestamp(),
    });
    setComment("");
  };

  useEffect(() => {
    setTimeout(() => {
      setOpen(user);
    }, 5000);
  }, []);

  useEffect(() => {
    let unsubscribe;
    if (Id) {
      unsubscribe = db
        .collection("posts")
        .doc(Id)
        .collection("comments")
        .orderBy("timestamp", "desc")
        .onSnapshot((snapshot) => {
          const tempComments = [];
          for (let doc of snapshot.docs) {
            tempComments.unshift(doc.data());
          }
          setModalComments(tempComments);
        });
    }
    setModal(true);
  }, [Id]);

  useEffect(() => {
    if (history.location.pathname === "/") history.replace("/home");
  }, []);

  useEffect(() => {
    posts.forEach((post) => {
      if (post.id === Id) {
        console.log(Id + " " + post.id);
        setValue((prev) => ({ ...prev, ...post }));
        setIsVal(true);
      }
    });
  }, [Id]);

  return (
    <>
      {/* Login warning */}
      {!user && (
        <Snackbar
          open={open}
          anchorOrigin={{
            vertical: "center",
            horizontal: "top",
          }}
        >
          <SnackbarContent
            style={{
              backgroundColor: "teal",
            }}
            message={<h2>Login or Signup to post and comment!</h2>}
          />
        </Snackbar>
      )}

      {/* // Displaying all posts */}
      {posts.map(({ id, post }) => (
        <Post
          setId={setId}
          key={id}
          postId={id}
          user={user}
          username={post.username}
          imageUrl={post.imageUrl}
          avatarURL={post.avatarURL}
          caption={post.caption}
        />
      ))}

      {/* // Modal for View all comments */}
      {isVal && (
        <Modal className={classes.modal} open={modalExp}>
          <div className={classes.modalContainer}>
            <div className={classes.modalHeader}>
              <h1 className={classes.modalUsername}>{value.post.username}</h1>
              <h1
                className={classes.closeModal}
                onClick={() => setModal(false)}
              >
                ✖
              </h1>
            </div>
            <div className={classes.modalMain}>
              <div className={classes.postImageHolder}>
                <div className={classes.postImageContainer}>
                  <img
                    src={value.post.imageUrl}
                    className={classes.postImage}
                  />
                </div>
              </div>

              <aside className={classes.commentContainer}>
                <div className={classes.postedComments}>
                  {modalComments &&
                    modalComments.map((comment, index) => (
                      <p key={`comment-index-${index}`}>
                        <strong> {comment.username} </strong> <br></br>
                        {comment.text}
                      </p>
                    ))}
                </div>
                <div className={classes.postCommentsContainer}>
                  {user && (
                    <form className={classes.postCommentBox}>
                      <input
                        className={classes.postCommentInput}
                        type="text"
                        placeholder="Add a comment.."
                        value={comment}
                        onChange={(e) => setComment(e.target.value)}
                      />
                      <button
                        className={classes.postCommentButton}
                        type="submit"
                        disabled={!comment}
                        onClick={postComment}
                      >
                        Post
                      </button>
                    </form>
                  )}
                </div>
              </aside>
            </div>
          </div>
        </Modal>
      )}
    </>
  );
}