@material-ui/core#InputLabel JavaScript Examples

The following examples show how to use @material-ui/core#InputLabel. 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: examples.js    From Queen with MIT License 6 votes vote down vote up
Examples = ({ selected, setSelected, className }) => {
  const classes = useStyles();
  const handleChange = event => {
    setSelected(event.target.value);
  };
  return (
    <FormControl className={`${classes.formControl} ${className}`}>
      <InputLabel htmlFor="native-simple">{D.labelExample}</InputLabel>
      <Select
        native
        value={selected}
        onChange={handleChange}
        inputProps={{
          name: 'questionnaire',
          id: 'native-simple',
        }}
      >
        <option value="">{D.labelExamples}</option>
        {QUESTIONNAIRE_EXAMPLES.map(v => {
          return (
            <option key={v} value={v}>
              {v.toUpperCase()}
            </option>
          );
        })}
      </Select>
    </FormControl>
  );
}
Example #2
Source File: KailonaSelect.js    From ehr with GNU Affero General Public License v3.0 6 votes vote down vote up
render() {
        return (
            <FormControl>
                <InputLabel htmlFor={this.props.name}>{this.props.name}</InputLabel>
                <Select
                    {...this.props}
                    inputProps={{
                        name: this.props.name,
                    }}
                >
                    {this.props.options.map(option => (
                        <option value={option.value}>{option.text}</option>
                    ))}
                </Select>
            </FormControl>
        );
    }
Example #3
Source File: SelectField.jsx    From archeage-tools with The Unlicense 6 votes vote down vote up
render() {
    const { id, label, value, renderValue, controlClassName } = this.props;
    let { options } = this.props;

    const entry = (key, value) => (
      <MenuItem key={`${id}-${key}`} value={key}>{value}</MenuItem>
    );

    if (options instanceof Map) {
      const opts = [];
      options.forEach((value, key) => opts.push(entry(key, value)));
      options = opts;
    } else if (Array.isArray(options)) {
      options = options.map(value => entry(value, value));
    } else {
      options = Object.entries(options).map(([key, value]) => entry(key, value));
    }

    return (
      <FormControl className={controlClassName}>
        {label &&
        <InputLabel htmlFor={id}>{label}</InputLabel>}
        <Select
          value={value}
          onChange={this.handleChange}
          inputProps={{
            name: id,
            id,
          }}
          renderValue={renderValue}
        >
          {options}
        </Select>
      </FormControl>
    );
  }
Example #4
Source File: form-util.js    From surveillance-forms with MIT License 6 votes vote down vote up
StatefulSelectField = ({ field }) => {
  const { label, property, onChange, disabled, choices } = field;

  const [value, setValue] = useState("");

  const handleChange = (event) => {
    const newValue = event.target.value;
    setValue(newValue);

    if (onChange) {
      onChange(newValue);
    }
  };

  return (
    <Box>
      <InputLabel shrink>{label}</InputLabel>
      <FormControl
        style={{
          width: "100%",
        }}
        variant="outlined"
        size="small"
      >
        <Select
          labelId={`label-${property}`}
          id={`select-${property}`}
          value={value}
          disabled={!!disabled}
          onChange={handleChange}
        >
          {choices.map((c, index) => (
            <MenuItem key={index} value={c.value}>
              {c.label}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </Box>
  );
}
Example #5
Source File: index.js    From hook-form-mui with MIT License 6 votes vote down vote up
StyledAutoSelectInputLabel = styled(InputLabel)`
  && {
    position: relative;
    .req-label {
      color: #f44336;
    }
    transform: translate(0, 1.5px) scale(0.75);
    transform-origin: top left;
  }
`
Example #6
Source File: AddGraph.js    From Interceptor with MIT License 6 votes vote down vote up
render() {
    //console.log("Rendering AddGraph");
    return (
      <Dialog
        open={this.props.show}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">Add Graph</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} direction="column" alignItems="center">
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="plotname">Plot Name</InputLabel>
                <Input
                  id="plotname"
                  onChange={event => this.plotname = event.target.value}
                  aria-describedby="plotname-helper-text"
                  inputProps={{
                    'aria-label': 'Plot Name',
                  }}
                />
                <FormHelperText id="plotname-helper-text">Can be left empty</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
            <ToggleButtonGroup orientation="vertical" value={this.lines} onChange={(event, lines) => {this.lines = lines; this.setState({render_revision: this.state.render_revision + 1}); } } aria-label="lines available">
              {this.renderButtons()}
            </ToggleButtonGroup>
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => this.props.addplot(this.plotname, this.lines)} color="default">
            Save
        </Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #7
Source File: index.js    From AED-Map with MIT License 6 votes vote down vote up
MySelect = ({
  label,
  labelTitle,
  options,
  variant,
  classes,
  ...props
}) => {
  const [field] = useField(props);
  const inputLabel = useRef(null);
  const [labelWidth, setLabelWidth] = useState(0);

  useEffect(() => {
    setLabelWidth(inputLabel.current.offsetWidth);
  }, []);

  return (
    <FormControl className={classes} variant={variant}>
      <InputLabel id={label} ref={inputLabel}>
        {labelTitle}
      </InputLabel>
      <Select
        labelId={label}
        labelWidth={labelWidth}
        {...field}
        {...props}
      >
        {options.map(option => (
          <MenuItem key={option} value={option}>
            {option || <em>всі</em>}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
}
Example #8
Source File: nav-sort.js    From horondi_admin with MIT License 6 votes vote down vote up
NavSort = ({ sortOptions }) => {
  const styles = useStyles();
  const { setSorting, sortLabel: sortLabelValue } = sortOptions;

  const selectOptions = _.map(sortOptions.labels, ({ label, value }) => (
    <MenuItem key={label} value={value}>
      {label}
    </MenuItem>
  ));

  const { optionHandler } = useSort(sortOptions.labels, setSorting);

  return (
    <div className={styles.sort}>
      <FormControl className={styles.formControl}>
        <InputLabel id={materialUiConstants.checkBoxLabel}>
          {sortLabel}
        </InputLabel>
        <Select
          data-cy='user-sorting'
          labelId='checkbox-label'
          id='checkbox'
          value={sortLabelValue}
          onChange={optionHandler}
          defaultValue={0}
        >
          {selectOptions}
        </Select>
      </FormControl>
    </div>
  );
}
Example #9
Source File: LeftPanel.js    From usfm-grammar-online with MIT License 5 votes vote down vote up
LeftPanel = (props) => {
  const { usfmValue, setUsfmValue, mode, setMode } = useContext(GrammarContext);
  const handleTextChange = (event) => {
    setUsfmValue(event.target.value);
  };

  const handleChange = (event) => {
    setMode(event.target.value);
  };

  return (
    <>
      <AppBar position="static" color="default">
        <Toolbar>
          <Box flexGrow={1} display="flex">
            <Link href="https://github.com/ubsicap/usfm" target="_blank">
              <Typography
                style={{
                  marginRight: 20,
                  color: "black",
                }}
                variant="h6"
              >
                USFM
              </Typography>
            </Link>
            <FormControl variant="outlined" style={{ width: 106 }}>
              <InputLabel id="demo-simple-select-outlined-label">
                Mode
              </InputLabel>

              <Select
                style={{ height: 37 }}
                labelId="demo-simple-select-outlined-label"
                id="demo-simple-select-outlined"
                value={mode}
                onChange={handleChange}
                label="Mode"
              >
                <MenuItem value="regular">Regular</MenuItem>
                <MenuItem value="relaxed">Relaxed</MenuItem>
              </Select>
            </FormControl>
            <ParseUsfm />
          </Box>
          <Upload setValue={setUsfmValue} type="usfm" />
          <Download extension="usfm" />
        </Toolbar>
      </AppBar>
      <CssTextField
        id="usfmText"
        placeholder="Enter/Upload USFM Text"
        onChange={handleTextChange}
        value={usfmValue}
      />
    </>
  );
}
Example #10
Source File: OperationForm.js    From Designer-Client with GNU General Public License v3.0 5 votes vote down vote up
export default function OperationForm(props) {
  const classes = useStyles();
  const operation = props.operation;

  return (
    <div className={classes.formContainer}>
      <div className={classes.formGroup}>
        <FormControl fullWidth={true}>
          <InputLabel htmlFor="operation-title">오퍼레이션 명칭</InputLabel>
          <Input id="operation-title" value={operation.title}></Input>
        </FormControl>
      </div>

      <div className={classes.formGroup}>
        <FormControl fullWidth={true}>
          <TextField
            id="operation-description"
            label="오퍼레이션 설명"
            multiline
            rows={5}
            value={operation.desc}
            aria-describedby="description-helper-text"
            name="description"
            placeholder="API 이용자에게 안내되는 설명글 입니다. 데이터의 이해를 위한 설명을 친절히 작성해 주세요."
          />
        </FormControl>
      </div>

      <div className={classes.formGroup}>
        <Grid container spacing={2}>
          <Grid item xs={12} sm={3}>
            <FormControl fullWidth={true}>
              <InputLabel width="100%" htmlFor="operation-method">
                호출 방식
              </InputLabel>
              <Select
                labelId="operation-method"
                id="namespace-input"
                name="method"
                value={operation.method || 'GET'}
              >
                <MenuItem value={"GET"}>GET</MenuItem>
              </Select>
              <FormHelperText id="operation-method-text">Http metod를 선택해주세요. 현재 GET 기능만 지원합니다.</FormHelperText>
            </FormControl>
          </Grid>

          <Grid item xs={12} sm={9}>
            <FormControl fullWidth={true}>
              <InputLabel width="100%" htmlFor="operation-end-point">호출 주소</InputLabel>
              <Input id="operation-end-point" value={operation.endPoint || ''} aria-describedby="entityName-helper-text" name="entityName" />
              <FormHelperText id="operation-end-point-text">{`https://OOOOOO.go.kr/api/APINAME/v1/TEST`}</FormHelperText>
            </FormControl>  
          </Grid>
        </Grid>
      </div>
    </div>
  )
}
Example #11
Source File: LinRegToolbox.js    From Otto with MIT License 5 votes vote down vote up
export default function LinRegToolbox() {
  const classes = useStyles();
  const { state } = useState();
  const { model_state, model_dispatch } = useModelState();
  const [indVar, setIndVar] = React.useState(model_state.linreg_x_name);

  React.useEffect(() => {
    setIndVar(model_state.linreg_x_name);
  }, [model_state.linreg_x_name]);

  function shouldRetrain() {
    return model_state.linreg_x_name !== indVar;
  }

  function onUpdatePlot() {
    model_dispatch({
      type: ModelActions.LINREG_SET_IND_VAR,
      linreg_x_name: indVar,
    });
    invokeLinReg(model_dispatch, state.sample_dataset, indVar, false);
  }

  return (
    <Card style={{ border: "none", boxShadow: "none" }}>
      <Grid direction="column" container>
        {/* Column 1 */}
        <Grid item className={classes.actionItem}>
          <FormControl className={classes.actionWidth}>
            <InputLabel id="demo-simple-select-label">
              Independent Variable
            </InputLabel>
            <Select
              value={indVar !== "" ? indVar : ""}
              onChange={(event) => setIndVar(event.target.value)}
            >
              {model_state.linreg_columns.map((column, index) => (
                <MenuItem key={index} value={column}>
                  {column}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>
        <Grid item>
          <Button
            color="primary"
            className={classes.button}
            variant="outlined"
            onClick={onUpdatePlot}
            disabled={!shouldRetrain()}
          >
            {"Re-Train Model"}
          </Button>
        </Grid>
      </Grid>
    </Card>
  );
}
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: SubthreaderDropdown.jsx    From se701-assignment1 with MIT License 5 votes vote down vote up
SubthreaderDropdown = ({
  retrievedSubthreaders,
  changeSubthread,
  pass,
  updateSubthreadersList,
}) => {
  const [thread, setThread] = React.useState('All');
  const [showModal, setModal] = useState(false);

  const handleChange = event => {
    setThread(event.target.value);
    changeSubthread(event.target.value);
  };
  let button;
  if (!pass) {
    button = (
      <div>
        <IconButton
          key="addButton"
          onClick={() => {
            setModal(true);
          }}
        >
          <AddOutlinedIcon id="add-button" />
        </IconButton>
        <CreateSubthreadModalServiced
          showModal={showModal}
          setModal={setModal}
          updateSubthreadersList={updateSubthreadersList}
        />
      </div>
    );
  }

  // Only loads on the home page
  if (!(window.location.pathname === '/')) return null;

  return (
    <div className="dropbox-parent">
      {button}
      <InputLabel className="child-elements" id="label">
        Subthreaders
      </InputLabel>
      <Select className="child-elements" labelId="label" value={thread} onChange={handleChange}>
        <MenuItem value="All"> All </MenuItem>
        {retrievedSubthreaders.map(sub => (
          <MenuItem value={sub.title}> {sub.title} </MenuItem>
        ))}
      </Select>
    </div>
  );
}
Example #14
Source File: form-util.js    From surveillance-forms with MIT License 5 votes vote down vote up
StatefulTextField = ({ field, clear }) => {
  const {
    label,
    property,
    onChange,
    disabled,
    onValidate,
    validationErrorMsg,
    focus,
  } = field;
  const [value, setValue] = useState(field.value || "");
  const [isValid, setIsValid] = useState(true);

  const firstUpdate = useRef(true); // dont run on mount

  useEffect(() => {
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }
    handleValidation();
  }, [value]);

  useEffect(() => {
    if (clear === 0) {
      return;
    }
    firstUpdate.current = true;
    setValue(field.value || "");
  }, [clear]);

  const handleChange = (event) => {
    const newValue = event.target.value;
    setValue(newValue);

    if (onChange) {
      onChange(newValue);
    }
  };

  const handleValidation = () => {
    if (onValidate) {
      const result = onValidate(value);
      setIsValid(result);
    }
  };

  const props = {};
  if (!isValid) {
    props["error"] = true;
    props["helperText"] = !isEmpty(validationErrorMsg)
      ? validationErrorMsg
      : "Incorrect Input";
  } else {
    props["error"] = undefined;
    props["helperText"] = undefined;
  }

  if (focus) {
    props["autoFocus"] = true;
  }

  return (
    <Box>
      <InputLabel shrink>{label}</InputLabel>
      <TextField
        color="#ffffff"
        id={`${property}-outlined`}
        value={value}
        onChange={handleChange}
        onBlur={handleValidation}
        disabled={!!disabled}
        fullWidth={true}
        autoComplete="false"
        size="small"
        variant="outlined"
        {...props}
      />
    </Box>
  );
}
Example #15
Source File: FeaturedPost.js    From alexa-community-jaipur with MIT License 5 votes vote down vote up
export default function FeaturedPost(props) {
  const classes = useStyles();
  const { post } = props;

  return (
    <Grid item xs={12} md={6}>
      <Card className={classes.card}>
        <div className={classes.cardDetails}>
          <CardContent>
            <Typography component="h2" variant="h5">
              {post.title}
            </Typography>
            <Typography variant="subtitle1" color="textSecondary">
              {post.date}
            </Typography>
            <Typography variant="subtitle1" paragraph>
              {post.description}
            </Typography>
            {post.suggestionPlaceholder ? (
              <Grid container direction="row">
                <FormControl>
                  <Grid item>
                    <InputLabel htmlFor="suggestions">
                      {post.suggestionPlaceholder}
                    </InputLabel>
                    <Input
                      id="suggestions"
                      aria-describedby="my-helper-suggestions"
                    />
                    <Button type="submit">Submit</Button>
                  </Grid>
                  <FormHelperText id="my-helper-suggestions">
                    We will try to cover the most asked topics.
                  </FormHelperText>
                </FormControl>
              </Grid>
            ) : null}
            {post.feedback ? (
              <Grid container direction="row">
                <FormControl>
                  <Grid item>
                    <InputLabel htmlFor="feedback">{post.feedback}</InputLabel>
                    <Input id="feedback" aria-describedby="my-helper-text" />
                    <Button type="submit">Submit</Button>
                  </Grid>
                  <FormHelperText id="my-helper-text">
                    Your feedback helps us improve.
                  </FormHelperText>
                </FormControl>
              </Grid>
            ) : null}
            <Typography variant="subtitle1" color="primary">
              <Button href="#" disabled={post.buttonDisable}>
                {post.buttonText}
              </Button>
            </Typography>
          </CardContent>
        </div>
        <Hidden xsDown>
          <CardMedia
            className={classes.cardMedia}
            image={post.image}
            title={post.imageTitle}
          />
        </Hidden>
      </Card>
    </Grid>
  );
}
Example #16
Source File: ContactFlow.js    From voicemail-for-amazon-connect with Apache License 2.0 5 votes vote down vote up
render() {

        let classes = this.props.classes;

        return(
            <div className={classes.root}>
                <h6 className={classes.title}>Generate Contact Flow</h6>
                <Grid className={classes.inputsContainer} container direction={"column"}>
                    <FormControl>
                        <InputLabel type={"text"} htmlFor="welcome-message">Welcome Message</InputLabel>
                        <Input id="welcome-message" disableUnderline={true} readOnly={false}  name={"welcomeMessage"}  value={this.state.welcomeMessage} onChange={this.handleInputChange}/>
                    </FormControl>
                    <FormControl>
                        <InputLabel htmlFor="fallback-queue-name">Fallback Queue</InputLabel>
                        <Input id="fallback-queue-name" disableUnderline={true} readOnly={false} name={"fallbackQueueName"} value={this.state.fallbackQueueName} onChange={this.handleInputChange}/>
                    </FormControl>
                    <FormControl>
                        <InputLabel type={"text"} htmlFor="default-error-message">Default Error Message</InputLabel>
                        <Input id="default-error-message" disableUnderline={true} readOnly={false}  name={"defaultErrorMessage"}  value={this.state.defaultErrorMessage} onChange={this.handleInputChange}/>
                    </FormControl>
                    <FormControl>
                        <InputLabel htmlFor="max-vm-duration">Max Voicemail Duration (sec.)</InputLabel>
                        <Input type={"number"} inputProps={{ min: "1", max: "120", step: "1" }} id="max-vm-duration" disableUnderline={true} readOnly={false} name={"maxVoicemailDuration"}  value={this.state.maxVoicemailDuration} onChange={this.handleInputChange}/>
                    </FormControl>
                    <FormControl>
                        <InputLabel htmlFor="loop-count">Incorrect Extension Loop Count</InputLabel>
                        <Input type={"number"} inputProps={{ min: "0", max: "10", step: "1" }} id="loop-count" disableUnderline={true} readOnly={false} name={"errorLoopCount"} value={this.state.errorLoopCount} onChange={this.handleInputChange}/>
                    </FormControl>
                </Grid>
                {(this.props.downloadError) ?
                    <p className={classes.error}>
                        {this.props.downloadError}
                    </p> :
                    null
                }
                <Grid className={classes.padTop} container spacing={5} direction="row">
                    <Grid item>
                        <AsyncButton loading={this.props.downloading} color="primary" variant="contained" onClick={this.handleDownload} disabled={this.props.userRole != "Administrator"}>Download</AsyncButton>
                    </Grid>
                </Grid>
            </div>
        )

    }
Example #17
Source File: index.js    From hook-form-mui with MIT License 5 votes vote down vote up
StyledInputLabel = styled(InputLabel)`
  && {
    .req-label {
      color: #f44336;
    }
  }
`
Example #18
Source File: GraphSettings.js    From Interceptor with MIT License 5 votes vote down vote up
render() {
    //console.log("Rendering GraphSettings");
    return (
      <Dialog
        open={this.props.show}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">Graphs settings</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} direction="column" alignItems="flex-start">
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="cols">Graph columns</InputLabel>
                <Input
                  id="cols"
                  value={this.state.cols}
                  onChange={event => this.setState({ cols: Math.min(Math.max(parseInt(event.target.value), 1), 12) })}
                  aria-describedby="cols-helper-text"
                  inputProps={{
                    'aria-label': 'Graph columns',
                  }}
                />
                <FormHelperText id="cols-helper-text">Max: 12</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="rateHz">Render rate</InputLabel>
                <Input
                  id="rateHz"
                  value={this.state.rateHz}
                  onChange={event => this.setState({ rateHz: Math.min(Math.max(parseInt(event.target.value), 0.5), 20) })}
                  endAdornment={<InputAdornment position="end">Hz</InputAdornment>}
                  aria-describedby="rateHz-helper-text"
                  inputProps={{
                    'aria-label': 'Render rate',
                  }}
                />
                <FormHelperText id="rateHz-helper-text">Min: 0.5, Max: 20</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControl>
                <InputLabel htmlFor="max_datapoints">Max data points</InputLabel>
                <Input
                  id="max_datapoints"
                  value={this.state.max_datapoints}
                  onChange={event => this.setState({ max_datapoints: Math.min(Math.max(parseInt(event.target.value), 20), 10000) })}
                  aria-describedby="max_datapoints-helper-text"
                  inputProps={{
                    'aria-label': 'Max data points',
                  }}
                />
                <FormHelperText id="max_datapoints-helper-text">Max: 10000</FormHelperText>
              </FormControl>
            </Grid>
            <Grid item>
              <FormControlLabel
                control={<Switch checked={this.state.webgl} onChange={() => this.setState({ webgl: !this.state.webgl })} name="webGL" />}
                label="WebGL support"
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => this.props.setSettings(this.state.cols, this.state.rateHz, this.state.max_datapoints, this.state.webgl)} color="default">
            Save
        </Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #19
Source File: FilterHelper.js    From theouterrim with MIT License 5 votes vote down vote up
render() {
    let { filterIndex, column, fieldLabel } = this.props
    return (
      <Grid xs={12}>
        <InputLabel shrink>{fieldLabel}</InputLabel>
        <FormGroup row style={{ justifyContent: "space-between", marginTop: 16 }}>
          <TextField
            style={{
              flex: "0 1 45%",
            }}
            type="number"
            placeholder="Min"
            value={this.state.minVal}
            onChange={evt => {
              this.setState({ minVal: evt.target.value })
              this.debouncedChange(
                [evt.target.value, this.state.maxVal],
                filterIndex,
                column
              )
            }}
          />
          <TextField
            style={{
              flex: "0 1 45%",
            }}
            type="number"
            placeholder="Max"
            value={this.state.maxVal}
            onChange={evt => {
              this.setState({ maxVal: evt.target.value })
              this.debouncedChange(
                [this.state.minVal, evt.target.value],
                filterIndex,
                column
              )
            }}
          />
        </FormGroup>
      </Grid>
    )
  }
Example #20
Source File: ChangeStatus.js    From eSim-Cloud with GNU General Public License v3.0 5 votes vote down vote up
function ChangeStatus ({ project, changedStatus }) {
  const dispatch = useDispatch()
  const [status, setStatus] = React.useState(null)
  const [note, setNote] = React.useState('')
  const handleSelectChange = (event) => {
    setStatus(event.target.value)
  }
  const clickChangeStatus = () => {
    dispatch(changeStatus(project.details.project_id, status, note))
    changedStatus()
  }
  const onChangeNote = (e) => {
    setNote(e.target.value)
  }
  useEffect(() => {
    dispatch(getStatus(project.details?.project_id))
  }, [dispatch, project.details])
  return (
    <Paper>
      {project.states &&
                <div style={{ padding: ' 0 1% 1% 1%', textAlign: 'left' }}>
                  <br />
                  <h3 style={{ marginTop: '0' }}>Review the project and change it&apos;s state</h3>
                  <h3 style={{ marginTop: '0' }}>Current State : {project.details?.status_name}</h3>
                  <TextField
                    style={{ width: '50%', marginBottom: '2%' }}
                    placeholder='Reviewer Notes'
                    multiline
                    value={note}
                    onChange={onChangeNote}
                    rows={2} />
                  <InputLabel style={{ marginTop: '0' }}>Select and Change the status of this project</InputLabel>
                  <Select
                    labelId="demo-simple-select-label"
                    id="demo-simple-select"
                    style={{ width: '50%' }}
                    onChange={handleSelectChange}
                    value={status}
                  >
                    {project.states.map((item, index) =>
                      (
                        <MenuItem key={item} value={item}>{item}</MenuItem>
                      ))}
                  </Select>
                  <Button style={{ float: 'right' }} variant='contained' color='primary' onClick={clickChangeStatus}>Change Status</Button>
                </div>
      }
    </Paper>
  )
}
Example #21
Source File: nav-filter-by-values.js    From horondi_admin with MIT License 5 votes vote down vote up
NavFilterByValues = ({
  filterByMultipleOptions: {
    filters,
    setFilterHandler,
    label,
    selectItems,
    objForTranslateRenderItems
  }
}) => {
  const styles = useStyles();

  const { optionHandler, setRenderValue } = useFilter(
    selectItems,
    setFilterHandler
  );

  return (
    <div className={styles.formblock}>
      <Badge
        badgeContent={filters.length}
        color={materialUiConstants.styleError}
        anchorOrigin={badgePosition}
      >
        <FormControl style={{ minWidth: 170 }} className={styles.formControl}>
          <InputLabel id={materialUiConstants.checkBoxLabel}>
            {label}
          </InputLabel>
          <Select
            labelId={materialUiConstants.checkBoxLabel}
            id={materialUiConstants.checkBoxId}
            multiple
            value={filters}
            onChange={optionHandler}
            renderValue={(selected) =>
              setRenderValue(selected, objForTranslateRenderItems)
            }
            input={<Input />}
            autoWidth
            MenuProps={MenuProps}
          >
            {selectItems.map((item) => (
              <MenuItem key={item.key} value={item.key}>
                <Checkbox checked={filters.indexOf(item.key) > -1} />
                <ListItemText primary={item.value} />
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      </Badge>
    </div>
  );
}
Example #22
Source File: Header.js    From React-GitHub-Resume with MIT License 5 votes vote down vote up
Header = () => {
  const classes = useStyles();
  const [languageCode, setLanguageCode] = useState('en');

  const handleChangeLanguage = ({ target: { value } }) => {
    setLanguageCode(value);
    i18n.changeLanguage(value);

    if (
      window
      && window.localStorage
    ) {
      window.localStorage.setItem('REACT_GITHUB_PROFILE_LANG', value);
    }
  }

  useEffect(() => {
    if (
      window
      && window.localStorage
    ) {
      const lang = window.localStorage.getItem('REACT_GITHUB_PROFILE_LANG');
      setLanguageCode(lang || 'en');
    }
  }, []);

  useEffect(() => {
    i18n.changeLanguage(languageCode);
  }, [languageCode]);

  return (
    <Grid
      container
      className={classes.container}
    >
      <Grid
        className={classes.languageWrapper}
      >
        <InputLabel
          id="demo-simple-select-label"
          className={classes.languageLabel}
        >
            Languages
        </InputLabel>
        <Select
          labelId="demo-simple-select-filled-label"
          id="demo-simple-select-filled"
          value={languageCode}
          onChange={handleChangeLanguage}
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          {
            languages.length > 0
            ?
              languages.map((item, index) => {
                return (
                  <MenuItem
                    key={index.toString()}
                    value={item.code}
                  >
                    {item.nativeName}
                  </MenuItem>
                )
              })
            : null
          }
        </Select>
      </Grid>
    </Grid>
  )
}
Example #23
Source File: AdminActivityList.js    From AdaptivApps-fe with MIT License 4 votes vote down vote up
AdminActivityList = props => {
  const classes = useStyles();
  // Grab the event id from props
  const event_id = props.event_id;
  // Call backend to fetch the one event associated with event id
  const { data, refetch } = useQuery(GET_ONE_EVENT, {
    variables: {
      id: event_id,
    },
  });

  // Declares C, U, and D for activities
  const [CreateActivity] = useMutation(CREATE_ACTIVITY);
  const [UpdateActivity] = useMutation(UPDATE_ACTIVITY);
  const [DeleteActivity] = useMutation(DELETE_ACTIVITY);

  // Similar to its parent component, activities list will be displayed
  // Using material table.
  return (
    <Grid>
      <MaterialTable
        title=""
        columns={[
          {
            title: "Name",
            field: "name",
            editComponent: props => (
              <>
                <Input
                  type="text"
                  value={props.value}
                  onChange={e => props.onChange(e.target.value)}
                />
                <InputLabel className={classes.label}>*Required</InputLabel>
              </>
            ),
          },
          {
            title: "Date",
            field: "startDate",
            editComponent: props => (
              <>
                <Input
                  type="date"
                  value={props.value}
                  onChange={e => props.onChange(e.target.value)}
                />
                <InputLabel className={classes.label}>*Required</InputLabel>
              </>
            ),
          },
          {
            title: "Time",
            field: "startTime",
            editComponent: props => (
              <>
                <Input
                  type="time"
                  value={props.value}
                  onChange={e => props.onChange(e.target.value)}
                />
                <InputLabel className={classes.label}>*Required</InputLabel>
              </>
            ),
          },
          {
            title: "Location",
            field: "location",
            editComponent: props => (
              <Input
                type="text"
                value={props.value}
                onChange={e => props.onChange(e.target.value)}
              />
            ),
          },
          {
            title: "Link",
            field: "link",
            render: rowData => (
              <div
                style={{
                  fontSize: "1.4rem",
                  width: "22rem",
                  overflow: "scroll",
                }}
              >
                {rowData.link}
              </div>
            ),
            editComponent: props => (
              <Input
                type="text"
                value={props.value}
                onChange={e => props.onChange(e.target.value)}
              />
            ),
          },
          {
            title: "Type",
            field: "type",
            editComponent: props => (
              <Input
                type="text"
                value={props.value}
                onChange={e => props.onChange(e.target.value)}
              />
            ),
          },
          {
            title: "Details",
            field: "details",
            render: rowData => (
              <div
                style={{
                  fontSize: "1.4rem",
                  width: "30rem",
                  maxHeight: "13rem",
                  overflow: "scroll",
                }}
              >
                {rowData.details}
              </div>
            ),
            editComponent: props => (
              <textarea
                style={{
                  fontSize: "1.4rem",
                }}
                rows="7"
                cols="60"
                type="text"
                value={props.value}
                onChange={e => props.onChange(e.target.value)}
              />
            ),
          },
        ]}
        data={data?.event?.activities}
        editable={{
          onRowAdd: async newData => {
            await CreateActivity({
              variables: {
                name: newData.name,
                startDate: newData.startDate,
                startTime: newData.startTime,
                location: newData.location,
                link: newData.link,
                type: newData.type,
                details: newData.details,
                event_id: event_id,
              },
            });
            refetch();
          },
          onRowUpdate: async (newData, oldData) => {
            await UpdateActivity({
              variables: {
                id: oldData.id,
                name: newData.name,
                startDate: newData.startDate,
                startTime: newData.startTime,
                location: newData.location,
                link: newData.link,
                type: newData.type,
                details: newData.details,
              },
            });
            refetch();
          },
          onRowDelete: async oldData => {
            await DeleteActivity({
              variables: {
                id: oldData.id,
              },
            });
            refetch();
          },
        }}
        icons={{
          Add: () => (
            <>
              <AddCircleOutlineIcon
                style={{ color: "#2962FF" }}
                fontSize="large"
              />
              <Button className={classes.addBtn}>Add Activity</Button>
            </>
          ),
          Edit: () => (
            <EditIcon style={{ color: "#2962FF" }} fontSize="large" />
          ),
          Delete: () => (
            <DeleteIcon style={{ color: "#2962FF" }} fontSize="large" />
          ),
        }}
        options={{
          cellStyle: {
            fontSize: "1.4rem",
          },
          headerStyle: {
            fontSize: "3.4rem",
            backgroundColor: "#2962FF",
            color: "#FFF",
          },
          search: false,
          showTitle: true,
          paging: false,
          emptyRowsWhenPaging: false,
          toolbarButtonAlignment: "left",
        }}
      />
    </Grid>
  );
}
Example #24
Source File: educationFormTemplate.js    From resumeker-fe with MIT License 4 votes vote down vote up
function EducationFormTemplate(props) {
  const classes = useStyles();

  return (
    <div className={classes.textField}>
      <FormControl className={classes.selectorForm} id="formSelector">
        <InputLabel
          data-testid="label"
          className={classes.selectorText}
          id="typeSelector"
        >
          Education
        </InputLabel>
        <Select
          className={classes.textField}
          variant="outlined"
          fullWidth
          id="type"
          label="Education"
          name="type"
          autoFocus
          onChange={props.onChange}
          value={props.info.type}
        >
          <MenuItem value={"UNDERGRADUATE"}>College</MenuItem>
          <MenuItem value={"GRADUATE"}>Graduate</MenuItem>
          <MenuItem value={"CERTIFICATION"}>Certification</MenuItem>
          <MenuItem value={"COURSE"}>Course</MenuItem>
        </Select>
      </FormControl>
      <TextField
        variant="outlined"
        margin="normal"
        fullWidth
        name="schoolName"
        label="Name of the school"
        id="schoolName"
        onChange={props.onChange}
        value={props.info.schoolName}
      />
      <TextField
        variant="outlined"
        margin="normal"
        fullWidth
        name="yearIn"
        type="date"
        // data-date-format="mm-dd-yyyy"
        label="School Starting Date"
        id="yearIn"
        InputLabelProps={{
          shrink: true,
        }}
        onChange={props.onChange}
        value={props.info.yearIn}
      />
      <TextField
        variant="outlined"
        margin="normal"
        fullWidth
        type="date"
        // data-date-format="mm-dd-yyyy"
        name="yearOut"
        label="Finishing School"
        id="yearOut"
        InputLabelProps={{
          shrink: true,
        }}
        onChange={props.onChange}
        value={props.info.yearOut}
      />
      <TextField
        variant="outlined"
        margin="normal"
        fullWidth
        name="certificateName"
        label="Name of the certificate"
        id="certificateName"
        onChange={props.onChange}
        value={props.info.certificateName}
      />
    </div>
  );
}
Example #25
Source File: CreatePostModal.js    From social-media-strategy-fe with MIT License 4 votes vote down vote up
CreatePostModal = (props) => {
	const { listId, open, handleClose } = props;
	const { content, formControl } = useStyles();
	const dispatch = useDispatch();
	const { lists } = useSelector((state) => state.kanban);
	const [post, setPost] = useState({
		list_id: "",
		post_text: "",
	});

	useEffect(() => {
		if (lists) {
			const drafts = Object.values(lists).find(
				(list) => list.title === "Drafts",
			);

			if (!drafts) {
				// create Drafts list
				(async () => {
					await dispatch(addList("Drafts"));
				})();
			} else {
				// set Drafts or listId from param as default list
				setPost((prevPost) => ({
					...prevPost,
					list_id: listId ? listId : drafts.id,
				}));
			}
		}
	}, [lists, listId, dispatch]);

	const handlePostText = (e) => {
		// Check if Enter was pressed
		if (e.keyCode === 13) {
			handleCreatePost(e);
		} else {
			const target = e.currentTarget;
			setPost((prevPost) => ({
				...prevPost,
				[target.id]: target.value?.trim(),
			}));
		}
	};

	const handleSelectList = (e) => {
		const target = e.target;

		setPost((prevPost) => ({
			...prevPost,
			list_id: target.value,
		}));
	};

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

		if (post.post_text) {
			dispatch(addPost(post));
			handleClose();
		}
	};

	return (
		<Dialog
			open={open}
			onClose={handleClose}
			aria-labelledby="form-dialog-title"
		>
			<DialogTitle id="form-dialog-title">Create a Post</DialogTitle>
			<DialogContent className={content}>
				{/* Post text */}
				<TextField
					autoFocus
					id="post_text"
					label="Post text"
					fullWidth
					multiline
					rows={4}
					rowsMax={7}
					variant="outlined"
					onChange={handlePostText}
					onKeyDown={handlePostText}
					inputProps={{
						maxLength: 280,
					}}
				/>
				<TwitterCharCount text={post.post_text} />

				{/* List Select */}
				<FormControl className={formControl}>
					<InputLabel id="list_label">Category</InputLabel>
					<Select
						labelId="list_label"
						id="list_select"
						value={post.list_id}
						onChange={handleSelectList}
					>
						{lists &&
							Object.values(lists).map((list) => {
								return (
									<MenuItem key={list.id} value={list.id}>
										{list.title}
									</MenuItem>
								);
							})}
					</Select>
				</FormControl>

				{/* Image upload */}
				{/* <input
            accept="image/*"
            style={{ display: "none" }}
            id="create-tweet"
            multiple
            type="file"
          />
          <label htmlFor="create-tweet">
            <AddAPhotoIcon />
          </label> */}
			</DialogContent>

			<DialogActions style={{ display: "flex", justifyContent: "flex-end" }}>
				<Button onClick={handleClose} color="primary">
					Cancel
				</Button>
				<Button onClick={handleCreatePost} color="primary">
					Add to List
				</Button>
			</DialogActions>
		</Dialog>
	);
}
Example #26
Source File: OnboardUser.jsx    From Corona-tracker with MIT License 4 votes vote down vote up
OnboardUser = props => {
  const {
    setDemographicsComorbiditiesThunk,
    demographicsComorbidities,
    tempUnit,
    currentObservations,
    setTempUnit,
  } = props;
  const { userSession } = useBlockstack();
  const classes = useStyles();
  const history = useHistory();
  const [formState, setFormState] = useState(onboardingInitialState.demographicsComorbidities);
  const [tempUnitChoice, setTempUnitChoice] = useState(tempUnit);

  useEffect(() => {
    setFormState(demographicsComorbidities);
  }, [demographicsComorbidities, setFormState]);

  const handleInputChange = e => {
    e.preventDefault();
    setFormState({
      ...formState,
      [e.target.name]: e.target.value,
    });
  };

  const handleSave = async () => {
    setTempUnit(userSession, currentObservations, tempUnit, tempUnitChoice);
    await setDemographicsComorbiditiesThunk(formState, userSession);
    history.push('/');
  };

  return (
    <Container maxWidth="xs" className={classes.root}>
      <Grid container spacing={1} alignItems="center">
        <Grid item xs={12}>
          <Typography variant="h5">
            <b>Welcome to CoronaTracker!</b>
          </Typography>
        </Grid>
        <Grid item xs={12}>
          <Typography variant="subtitle1" paragraph color="textSecondary">
            Let&apos;s get your profile set up with a few quick questions and start logging your health:
          </Typography>
        </Grid>
        <Grid item sm={4} xs={6}>
          <FormControl variant="outlined" className={classes.fullWidth}>
            <InputLabel id="gender-select-label">Gender</InputLabel>
            <Select
              labelId="gender-select-label"
              id="gender-select"
              name="gender"
              label="Gender"
              value={formState.gender}
              onChange={handleInputChange}
            >
              <MenuItem value="male">Male</MenuItem>
              <MenuItem value="female">Female</MenuItem>
              <MenuItem value="nonbinary">Non-Binary</MenuItem>
            </Select>
          </FormControl>
        </Grid>
        <Grid item sm={4} xs={6}>
          <TextField
            type="number"
            name="age"
            label="Age (Years)"
            value={formState.age}
            variant="outlined"
            fullWidth
            onChange={handleInputChange}
          />
        </Grid>
        <Grid item xs={12}>
          <TextField
            type="text"
            name="city"
            label="City"
            value={formState.city}
            variant="outlined"
            fullWidth
            onChange={handleInputChange}
          />
        </Grid>
        <Grid item sm={3} xs={6}>
          <FormControl variant="outlined" className={classes.fullWidth}>
            <InputLabel id="state-select-label">State</InputLabel>
            <Select
              labelId="state-select-label"
              id="state-select"
              label="State"
              name="state"
              value={formState.state}
              onChange={handleInputChange}
            >
              {states.map(state => (
                <MenuItem key={state.abbreviation} value={state.abbreviation}>
                  {state.abbreviation}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>
        <Grid item sm={5} xs={6}>
          <TextField
            type="text"
            name="zip"
            label="Zip Code"
            value={formState.zip}
            variant="outlined"
            fullWidth
            onChange={handleInputChange}
          />
        </Grid>
        <Grid item xs={5}>
          <Typography variant="body1" color="textSecondary">
            <b>Do you smoke?</b>
          </Typography>
        </Grid>
        <Grid item xs={6}>
          <ButtonGroup>
            <Button
              type="button"
              name="isSmoker"
              value="yes"
              onClick={handleInputChange}
              className={`${classes.buttonLeft} ${formState.isSmoker === 'yes' && classes.selectedButton}`}
            >
              Yes
            </Button>
            <Button
              type="button"
              name="isSmoker"
              value="no"
              onClick={handleInputChange}
              className={`${classes.buttonRight} ${formState.isSmoker === 'no' && classes.selectedButton}`}
            >
              No
            </Button>
          </ButtonGroup>
        </Grid>
        <Grid item xs={5}>
          <Typography variant="body1" color="textSecondary">
            <b>Are you Obese (BMI)?</b>
          </Typography>
        </Grid>
        <Grid item xs={6}>
          <ButtonGroup>
            <Button
              type="button"
              name="isObese"
              value="yes"
              onClick={handleInputChange}
              className={`${classes.buttonLeft} ${formState.isObese === 'yes' && classes.selectedButton}`}
            >
              Yes
            </Button>
            <Button
              type="button"
              name="isObese"
              value="no"
              onClick={handleInputChange}
              className={`${classes.buttonRight} ${formState.isObese === 'no' && classes.selectedButton}`}
            >
              No
            </Button>
          </ButtonGroup>
        </Grid>
        <Grid item xs={5}>
          <Typography variant="body1" color="textSecondary">
            <b>Do you have asthma?</b>
          </Typography>
        </Grid>
        <Grid item xs={6}>
          <ButtonGroup>
            <Button
              type="button"
              name="isAsthmatic"
              value="yes"
              onClick={handleInputChange}
              className={`${classes.buttonLeft} ${formState.isAsthmatic === 'yes' && classes.selectedButton}`}
            >
              Yes
            </Button>
            <Button
              type="button"
              name="isAsthmatic"
              value="no"
              onClick={handleInputChange}
              className={`${classes.buttonRight} ${formState.isAsthmatic === 'no' && classes.selectedButton}`}
            >
              No
            </Button>
          </ButtonGroup>
        </Grid>
        <Grid item xs={5}>
          <Typography variant="body1" color="textSecondary">
            <b>Preferred unit of measure?</b>
          </Typography>
        </Grid>
        <Grid item xs={6}>
          <ButtonGroup>
            <Button
              type="button"
              value="celsius"
              onClick={() => setTempUnitChoice('celsius')}
              className={`${classes.buttonLeft} ${tempUnitChoice === 'celsius' && classes.selectedButton}`}
            >
              &#8451;
            </Button>
            <Button
              type="button"
              value="fahrenheit"
              onClick={() => setTempUnitChoice('fahrenheit')}
              className={`${classes.buttonRight} ${tempUnitChoice === 'fahrenheit' && classes.selectedButton}`}
            >
              &#8457;
            </Button>
          </ButtonGroup>
        </Grid>
        <Grid item xs={12}>
          <Button className={classes.saveButton} onClick={handleSave}>
            Save my responses
          </Button>
        </Grid>
      </Grid>
    </Container>
  );
}
Example #27
Source File: EditQuiz.js    From Quizzie with MIT License 4 votes vote down vote up
function EditQuiz(props) {
	const quizId = props.match.params.id;

	const [loading, setLoading] = useState(true);
	const [redirect, setRedirect] = useState(false);

	const [quizDetails, setQuizDetails] = useState({});
	const [quizQuestions, setQuizQuestions] = useState([]);

	const [fileError, setFileError] = useState(false);
	const [serverError, setServerError] = useState(false);
	const [popoverAnchor, setPopoverAnchor] = useState(null);
	const popoverOpen = Boolean(popoverAnchor);

	const [questionModal, setQuestionModal] = useState(false);
	const [newQuestion, setNewQuestion] = useState("");
	const [newQuestionError, setNewQuestionError] = useState(false);

	const [option1, setOption1] = useState("");
	const [option1Error, setOption1Error] = useState(false);
	const [option2, setOption2] = useState("");
	const [option2Error, setOption2Error] = useState(false);
	const [option3, setOption3] = useState("");
	const [option3Error, setOption3Error] = useState(false);
	const [option4, setOption4] = useState("");
	const [option4Error, setOption4Error] = useState(false);
	const [correctOption, setCorrectOption] = useState(-1);
	const [correctOptionError, setCorrectOptionError] = useState(false);

	const [update, setUpdate] = useState(false);
	const [updateId, setUpdateId] = useState(null);

	const [deleteModal, setDeleteModal] = useState(false);
	const [deleteQuestionModal, setDeleteQuestionModal] = useState(false);

	const [quizRestartModal, setQuizRestartModal] = useState(false);
	const [closeQuizModal, setCloseQuizModal] = useState(false);

	const [responses, setResponses] = useState([]);

	const [searchData, setSearchData] = useState(responses);
	const [searchText, setSearchText] = useState("");
	const [sortBy, setSortBy] = useState(-1);

	const { executeRecaptcha } = useGoogleReCaptcha();

	const onCloseHandle = () => {
		setQuestionModal(false);
		if (update) {
			setUpdate(false);
			setUpdateId(null);
			clearModal();
		}
	};

	const handlePopover = (event) => {
		setPopoverAnchor(event.currentTarget);
	};

	const handlePopoverClose = () => {
		setPopoverAnchor(null);
	};

	const onQuestionChange = (event) => {
		setNewQuestion(event.target.value);
	};

	const handleOptionChange1 = (event) => {
		setOption1(event.target.value);
	};
	const handleOptionChange2 = (event) => {
		setOption2(event.target.value);
	};
	const handleOptionChange3 = (event) => {
		setOption3(event.target.value);
	};
	const handleOptionChange4 = (event) => {
		setOption4(event.target.value);
	};

	const handleCorrectOption = (event) => {
		setCorrectOption(event.target.value);
	};

	const clearModal = () => {
		setNewQuestion("");
		setNewQuestionError(false);
		setOption1("");
		setOption1Error(false);
		setOption2("");
		setOption2Error(false);
		setOption3("");
		setOption3Error(false);
		setOption4("");
		setOption4Error(false);
		setCorrectOption(-1);
		setCorrectOptionError(false);
	};

	const handleFileDrop = (files) => {
		const reader = new FileReader();

		let questions = [];

		reader.onabort = () => {
			setFileError(true);
			return;
		};
		reader.onerror = () => {
			setFileError(true);
			return;
		};

		reader.onload = () => {
			csv.parse(reader.result, (err, data) => {
				if (data === undefined) {
					setFileError(true);
					return;
				}
				data.map((question) => {
					if (question[0].trim() === "") {
						return null;
					}
					let obj = {
						quizId: quizId,
						description: question[0],
						options: [
							{ text: question[1] },
							{ text: question[2] },
							{ text: question[3] },
							{ text: question[4] },
						],
						correctAnswer: question[5],
					};

					questions.push(obj);
				});
				submitCSV(questions);
			});
		};

		reader.readAsBinaryString(files[0]);
	};

	const submitCSV = async (questions) => {
		setLoading(true);
		let token = localStorage.getItem("authToken");
		let url = "https://quizzie-api.herokuapp.com/question/csv";

		let captcha = await executeRecaptcha("submit_csv");

		let data = {
			questions: questions,
			captcha: captcha,
		};

		try {
			await axios
				.post(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					console.log(res);
					setLoading(false);
					clearModal();
					onCloseHandle();
					getQuizDetails();
				});
		} catch (error) {
			setServerError(true);
			console.log(error);
		}
	};

	const handleSearchChange = (event) => {
		setSearchText(event.target.value);

		let newRes = responses.filter(
			(response) =>
				response.userId.name
					.toLowerCase()
					.search(event.target.value.trim().toLowerCase()) !== -1 ||
				String(response.marks) ===
					event.target.value.trim().toLowerCase()
		);
		let sorted = sortByFunc(sortBy, newRes);

		setSearchData(sorted);
	};

	const handleSortChange = (event) => {
		setSortBy(event.target.value);

		let newRes = sortByFunc(event.target.value, searchData);

		setSearchData(newRes);
	};

	const sortByFunc = (by, array) => {
		if (by === "score") {
			return array.sort(function (a, b) {
				return b.marks - a.marks;
			});
		} else if (by === "name") {
			return array.sort(function (a, b) {
				return a.userId.name - b.userId.name;
			});
		} else if (by === "recent") {
			return array.sort(function (a, b) {
				return b.timeEnded - a.timeEnded;
			});
		} else {
			return array;
		}
	};

	const handleRestart = async () => {
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/restart`;

		let captcha = await executeRecaptcha("restart_quiz");

		let data = {
			quizId: quizId,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setQuizRestartModal(false);
					getQuizDetails();
				});
		} catch (error) {
			console.log(error);
		}
	};

	const handleQuizClose = async () => {
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/close`;

		let captcha = await executeRecaptcha("quiz_close");

		let data = {
			quizId: quizId,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setCloseQuizModal(false);
					getQuizDetails();
				});
		} catch (error) {
			console.log(error);
		}
	};

	const handleQuestionEditBtn = (question) => {
		setUpdate(true);
		setUpdateId(question._id);
		setNewQuestion(question.description);
		setOption1(question.options[0].text);
		setOption2(question.options[1].text);
		setOption3(question.options[2].text);
		setOption4(question.options[3].text);
		setCorrectOption(question.correctAnswer);
		setQuestionModal(true);
	};

	const handleQuestionDeleteBtn = (question) => {
		setUpdateId(question._id);
		setDeleteQuestionModal(true);
	};

	const handleQuestionModalClose = () => {
		setUpdateId(null);
		setDeleteQuestionModal(false);
	};

	const handleDeleteBtn = () => {
		setDeleteModal(true);
	};

	const handleDeleteQuestion = async () => {
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/question/${updateId}`;

		// let captcha = executeRecaptcha("delete_quiz");

		try {
			await axios
				.delete(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setUpdateId(null);
					setDeleteQuestionModal(false);
					getQuizDetails();
				});
		} catch (error) {
			console.log(error);
		}
	};

	const handleDelete = async () => {
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/delete`;

		let data = {
			quizId: quizId,
		};

		try {
			await axios
				.delete(url, {
					headers: {
						"auth-token": token,
					},
					data: data,
				})
				.then((res) => {
					setRedirect(true);
				});
		} catch (error) {
			console.log(error);
		}
	};

	const handleQuestionUpdate = async () => {
		if (!validate()) return;

		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/question/update/${updateId}`;

		let captcha = await executeRecaptcha("question_update");

		let updateOps = [
			{ propName: "description", value: newQuestion },
			{
				propName: "options",
				value: [
					{
						text: option1,
					},
					{
						text: option2,
					},
					{
						text: option3,
					},
					{
						text: option4,
					},
				],
			},
			{ propName: "correctAnswer", value: correctOption },
		];

		let data = {
			updateOps: updateOps,
			captcha: captcha,
		};

		try {
			await axios
				.patch(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					onCloseHandle();
					getQuizDetails();
				});
		} catch (error) {
			console.log(error);
		}
	};

	const validate = () => {
		if (newQuestion.trim().length === 0) {
			setNewQuestionError(true);
			return false;
		}

		if (option1.trim().length === 0) {
			setOption1Error(true);
			return false;
		}
		if (option2.trim().length === 0) {
			setOption2Error(true);
			return false;
		}
		if (option3.trim().length === 0) {
			setOption3Error(true);
			return false;
		}
		if (option4.trim().length === 0) {
			setOption4Error(true);
			return false;
		}

		if (correctOption === -1) {
			setCorrectOptionError(true);
			return false;
		}

		return true;
	};

	const handleQuestionSubmit = async () => {
		//TODO: Handle Validation

		if (!validate()) return;

		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/question/add`;

		let captcha = await executeRecaptcha("submit_question");

		let options = [
			{ text: option1 },
			{ text: option2 },
			{ text: option3 },
			{ text: option4 },
		];

		let data = {
			quizId: quizId,
			description: newQuestion,
			options: options,
			correctAnswer: correctOption,
			captcha: captcha,
		};

		try {
			await axios
				.post(url, data, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					clearModal();
					getQuizDetails();
					setQuestionModal(false);
				});
		} catch (error) {
			console.log(error);
		}
	};

	const isOwnerOfQuiz = async () => {
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/checkAdmin/${quizId}`;

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					return true;
				});
		} catch (error) {
			setRedirect(true);
			return;
		}
	};

	const getQuizDetails = async () => {
		setLoading(true);
		let token = localStorage.getItem("authToken");
		let url = `https://quizzie-api.herokuapp.com/quiz/${quizId}`;

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setQuizDetails(res.data.result);
				});
		} catch (error) {
			console.log(error);
		}

		url = `https://quizzie-api.herokuapp.com/question/all/${quizId}`;

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setQuizQuestions(res.data.result);
				});
		} catch (error) {
			console.log(error);
		}

		url = `https://quizzie-api.herokuapp.com/admin/allStudentsQuizResult/${quizId}`;

		try {
			await axios
				.get(url, {
					headers: {
						"auth-token": token,
					},
				})
				.then((res) => {
					setResponses(res.data.userResults);
					setSearchData(res.data.userResults);
					setLoading(false);
				});
		} catch (error) {
			console.log(error);
		}
	};

	useEffect(() => {
		let token = localStorage.getItem("authToken");
		if (token === null) {
			setLoading(false);
			setRedirect(true);
			return;
		}

		isOwnerOfQuiz();
		getQuizDetails();
	}, []);

	if (loading) {
		return <Loading />;
	} else if (redirect) {
		return <Redirect to="/dashboard" />;
	} else {
		return (
			<Container className="edit-quiz-page">
				<Typography
					variant="h3"
					className="dash-head p-top edit-quiz-head"
				>
					Edit Quiz
				</Typography>
				<div className="edit-btn-bar">
					<Button
						className="edit-details-btn"
						component={Link}
						to={`/updateQuizDetails/${quizId}`}
					>
						<Create className="edit-icon" />
						Edit Details
					</Button>
					<Button
						className="edit-details-btn delete-btn"
						onClick={handleDeleteBtn}
					>
						<Delete className="edit-icon" />
						Delete Quiz
					</Button>
					{quizDetails.quizStatus === 1 ? (
						<Button
							className="edit-details-btn"
							style={{ marginLeft: "3%" }}
							onClick={() => setCloseQuizModal(true)}
						>
							<Replay className="edit-quiz" />
							Close Quiz
						</Button>
					) : quizDetails.quizStatus === 2 ? (
						<Button
							className="edit-details-btn"
							style={{ marginLeft: "3%" }}
							onClick={() => setQuizRestartModal(true)}
						>
							<Replay className="edit-quiz" />
							Restart Quiz
						</Button>
					) : null}
				</div>
				<div className="quiz-details-sec">
					<Typography variant="h6" className="quiz-detail-param">
						Name:{" "}
						<span className="quiz-detail-text">
							{quizDetails.quizName}
						</span>
					</Typography>
					<Typography variant="h6" className="quiz-detail-param">
						Date:{" "}
						<span className="quiz-detail-text">
							{new Date(
								Number(quizDetails.scheduledFor)
							).toDateString()}
						</span>
					</Typography>
					<Typography variant="h6" className="quiz-detail-param">
						Time:{" "}
						<span className="quiz-detail-text">
							{new Date(
								Number(quizDetails.scheduledFor)
							).toLocaleTimeString()}
						</span>
					</Typography>
					<Typography variant="h6" className="quiz-detail-param">
						Duration:{" "}
						<span className="quiz-detail-text">
							{quizDetails.quizDuration} minutes
						</span>
					</Typography>
					<Typography variant="h6" className="quiz-detail-param">
						Type:{" "}
						<span className="quiz-detail-text">
							{quizDetails.quizType}
						</span>
					</Typography>
					{quizDetails.quizType === "private" ? (
						<Typography variant="h6" className="quiz-detail-param">
							Quiz Code:{" "}
							<span className="quiz-detail-text">
								{quizDetails.quizCode}
							</span>
						</Typography>
					) : null}
				</div>
				<div className="quiz-questions-sec">
					<Typography variant="h4" className="quiz-questions-head">
						Questions
					</Typography>
					<div className="quiz-questions-display">
						<div className="add-question-bar">
							<Button
								className="add-question-btn"
								onClick={() => setQuestionModal(true)}
							>
								Add a question
							</Button>
						</div>
						{quizQuestions.length === 0 ? (
							<p style={{ textAlign: "center" }}>
								No questions added yet!
							</p>
						) : (
							<div className="questions-list-display">
								{quizQuestions.map((question) => (
									<ExpansionPanel
										elevation={3}
										className="expansion"
										key={question._id}
									>
										<ExpansionPanelSummary
											className="question-summary"
											expandIcon={<ExpandMore />}
											aria-controls="question-content"
											aria-label="Expand"
										>
											<FormControlLabel
												style={{ marginRight: "0" }}
												aria-label="Edit"
												control={
													<IconButton>
														<Create />
													</IconButton>
												}
												// label={question.description}
												onClick={() =>
													handleQuestionEditBtn(
														question
													)
												}
											/>
											<FormControlLabel
												aria-label="Edit"
												control={
													<IconButton>
														<Delete />
													</IconButton>
												}
												// label={question.description}
												onClick={() =>
													handleQuestionDeleteBtn(
														question
													)
												}
											/>
											<Typography className="question-label">
												{question.description}
											</Typography>
										</ExpansionPanelSummary>
										<ExpansionPanelDetails>
											<List
												component="nav"
												className="options-display"
											>
												{question.options.map(
													(option) => (
														<ListItem
															button
															key={option._id}
														>
															<ListItemIcon>
																<Adjust
																	style={{
																		color:
																			question.correctAnswer ===
																			option.text
																				? "green"
																				: "black",
																	}}
																/>
															</ListItemIcon>
															<ListItemText
																style={{
																	color:
																		question.correctAnswer ===
																		option.text
																			? "green"
																			: "black",
																}}
																primary={
																	option.text
																}
															/>
														</ListItem>
													)
												)}
											</List>
										</ExpansionPanelDetails>
									</ExpansionPanel>
								))}
							</div>
						)}
					</div>
					<Typography
						variant="h4"
						className="quiz-questions-head m-top"
					>
						Submissions
					</Typography>
					<div className="quiz-students-list">
						<div className="add-question-bar">
							<Button
								className="add-question-btn stats-btn"
								component={
									responses.length !== 0 ? Link : Button
								}
								to={{
									pathname: "/quizStats",
									state: { responses: responses },
								}}
							>
								<BarChart />
								View Stats
							</Button>
						</div>
						{responses.length === 0 ? (
							<p
								style={{
									textAlign: "center",
									margin: "0",
									paddingTop: "3%",
									paddingBottom: "3%",
								}}
							>
								No responses yet!
							</p>
						) : (
							<>
								<div className="search-bar">
									<TextField
										placeholder="Search by name or score"
										type="text"
										onChange={handleSearchChange}
										className="search-input"
										value={searchText}
									/>
									<div style={{ marginLeft: "3%" }}>
										<InputLabel id="sort-by">
											Sort by
										</InputLabel>
										<Select
											labelId="sort-by"
											id="sort-select"
											value={sortBy}
											onChange={handleSortChange}
										>
											<MenuItem value={-1}>
												<em>None</em>
											</MenuItem>
											<MenuItem value="recent">
												Recent
											</MenuItem>
											<MenuItem value="score">
												Score
											</MenuItem>
											<MenuItem value="name">
												Name
											</MenuItem>
										</Select>
									</div>
								</div>
								<List aria-label="responses list">
									{searchData.map((response) => (
										<ListItem
											button
											key={response._id}
											component={Link}
											to={{
												pathname: `/studentResponse`,
												state: { response: response },
											}}
										>
											<ListItemText
												primary={response.userId.name}
												secondary={`Scored: ${response.marks}`}
											/>
										</ListItem>
									))}
								</List>
							</>
						)}
					</div>
				</div>
				<Dialog
					open={questionModal}
					onClose={onCloseHandle}
					aria-labelledby="add-question-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "#333",
							minWidth: "50%",
						},
					}}
					style={{ width: "100%" }}
				>
					<div className="add-ques-heading">
						<Typography
							variant="h6"
							style={{ textAlign: "center", margin: "2% 5%" }}
						>
							New Question{" "}
						</Typography>
						{!update ? (
							<IconButton onClick={handlePopover}>
								<Info className="add-info-icon" />
							</IconButton>
						) : null}
						<Popover
							id="file-upload-popover"
							open={popoverOpen}
							anchorEl={popoverAnchor}
							onClose={handlePopoverClose}
							anchorOrigin={{
								vertical: "bottom",
								horizontal: "left",
							}}
							disableRestoreFocus
							useLayerForClickAway={false}
							PaperProps={{ style: { maxWidth: "400px" } }}
						>
							<p className="popover-text">
								You can upload a <strong>.csv</strong> file with
								questions. The format should be: the{" "}
								<strong>
									first column should contain the question
									text.
								</strong>{" "}
								The next 4 columns must contain the{" "}
								<strong>four options.</strong> And the sixth
								column should contain{" "}
								<strong>
									the correct answer (it should match one of
									the four options)
								</strong>
								. <br />
								<br />
								<strong>
									NOTE: THE FILE SHOULD EXACTLY MATCH THE
									GIVEN FORMAT.
								</strong>{" "}
								You will be able to see and edit all the
								question though.
							</p>
						</Popover>
					</div>
					{!update ? (
						<>
							<div className="dropzone">
								<Dropzone
									onDrop={(acceptedFiles) =>
										handleFileDrop(acceptedFiles)
									}
								>
									{({ getRootProps, getInputProps }) => (
										<section>
											<div {...getRootProps()}>
												<input {...getInputProps()} />
												<AddCircle className="drop-icon" />
												<p
													style={{
														color:
															"rgb(110, 110, 110)",
													}}
												>
													Drag 'n' drop or click to
													select files
												</p>
											</div>
										</section>
									)}
								</Dropzone>
							</div>
							<p className="manual-head">
								<span>Or manually add the question</span>
							</p>
						</>
					) : null}
					<div className="new-question-form">
						<TextInput
							error={newQuestionError}
							helperText={
								newQuestionError ? "This cannot be empty" : null
							}
							className="new-ques-input"
							variant="outlined"
							label="Question Text"
							value={newQuestion}
							onChange={onQuestionChange}
						/>
						<hr style={{ width: "100%", marginBottom: "3%" }} />
						<Grid container spacing={1}>
							<Grid item xs={12} sm={6}>
								<TextInput
									error={option1Error}
									helperText={
										option1Error
											? "This cannot be empty"
											: null
									}
									className="new-ques-input"
									variant="outlined"
									label="Option 1"
									value={option1}
									onChange={handleOptionChange1}
								/>
							</Grid>
							<Grid item xs={12} sm={6}>
								<TextInput
									error={option2Error}
									helperText={
										option2Error
											? "This cannot be empty"
											: null
									}
									className="new-ques-input"
									variant="outlined"
									label="Option 2"
									value={option2}
									onChange={handleOptionChange2}
								/>
							</Grid>
						</Grid>
						<Grid container spacing={1}>
							<Grid item xs={12} sm={6}>
								<TextInput
									error={option3Error}
									helperText={
										option3Error
											? "This cannot be empty"
											: null
									}
									className="new-ques-input"
									variant="outlined"
									label="Option 3"
									value={option3}
									onChange={handleOptionChange3}
								/>
							</Grid>
							<Grid item xs={12} sm={6}>
								<TextInput
									error={option4Error}
									helperText={
										option4Error
											? "This cannot be empty"
											: null
									}
									className="new-ques-input"
									variant="outlined"
									label="Option 4"
									value={option4}
									onChange={handleOptionChange4}
								/>
							</Grid>
						</Grid>
						<hr style={{ width: "100%", marginBottom: "3%" }} />
						<InputLabel id="correct-option">
							Correct Option
						</InputLabel>
						<Select
							error={correctOptionError}
							className="correct-answer-select"
							style={{ width: "50%" }}
							labelId="correct-option"
							value={correctOption}
							onChange={handleCorrectOption}
						>
							<MenuItem value={-1}>None</MenuItem>
							{option1.trim().length !== 0 ? (
								<MenuItem value={option1}>{option1}</MenuItem>
							) : null}
							{option2.trim().length !== 0 ? (
								<MenuItem value={option2}>{option2}</MenuItem>
							) : null}
							{option3.trim().length !== 0 ? (
								<MenuItem value={option3}>{option3}</MenuItem>
							) : null}
							{option4.trim().length !== 0 ? (
								<MenuItem value={option4}>{option4}</MenuItem>
							) : null}
						</Select>
						{!update ? (
							<Button
								className="add-question-submit"
								onClick={handleQuestionSubmit}
							>
								Add Question
							</Button>
						) : (
							<Button
								className="add-question-submit"
								onClick={handleQuestionUpdate}
							>
								Update Question
							</Button>
						)}
					</div>
				</Dialog>
				<Dialog
					open={deleteModal}
					onClose={() => setDeleteModal(false)}
					aria-labelledby="delete-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "black",
							minWidth: "10%",
						},
					}}
				>
					<DialogTitle>
						Are you sure you want to delete this quiz?
					</DialogTitle>
					<div className="btn-div">
						<Button
							className="logout-btn m-right bg-red-btn"
							onClick={handleDelete}
						>
							Yes
						</Button>
						<Button
							className="cancel-btn m-left"
							onClick={() => setDeleteModal(false)}
						>
							No
						</Button>
					</div>
				</Dialog>
				<Dialog
					open={deleteQuestionModal}
					onClose={handleQuestionModalClose}
					aria-labelledby="delete-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "black",
							minWidth: "10%",
						},
					}}
				>
					<DialogTitle>
						Are you sure you want to delete this question?
					</DialogTitle>
					<div className="btn-div">
						<Button
							className="logout-btn m-right bg-red-btn"
							onClick={handleDeleteQuestion}
						>
							Yes
						</Button>
						<Button
							className="cancel-btn m-left"
							onClick={handleQuestionModalClose}
						>
							No
						</Button>
					</div>
				</Dialog>
				<Dialog
					open={quizRestartModal}
					onClose={() => setQuizRestartModal(false)}
					aria-labelledby="restart-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "black",
							minWidth: "10%",
						},
					}}
				>
					<DialogTitle>
						Are you sure you want to restart this quiz?
					</DialogTitle>
					<div className="btn-div">
						<Button
							className="logout-btn m-right bg-green-btn"
							onClick={handleRestart}
						>
							Yes
						</Button>
						<Button
							className="cancel-btn m-left bg-red-btn"
							onClick={() => setQuizRestartModal(false)}
						>
							No
						</Button>
					</div>
				</Dialog>
				<Dialog
					open={closeQuizModal}
					onClose={() => setCloseQuizModal(false)}
					aria-labelledby="restart-quiz-modal"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "black",
							minWidth: "10%",
						},
					}}
				>
					<DialogTitle>
						Are you sure you want to close this quiz?
					</DialogTitle>
					<div className="btn-div">
						<Button
							className="logout-btn m-right bg-green-btn"
							onClick={handleQuizClose}
						>
							Yes
						</Button>
						<Button
							className="cancel-btn m-left bg-red-btn"
							onClick={() => setCloseQuizModal(false)}
						>
							No
						</Button>
					</div>
				</Dialog>
				<Snackbar
					open={fileError}
					autoHideDuration={3000}
					onClose={() => setFileError(false)}
					anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setFileError(false)}
					>
						There was some problem with the file. Try again...
					</Alert>
				</Snackbar>
				<Snackbar
					open={serverError}
					autoHideDuration={3000}
					onClose={() => setServerError(false)}
					anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setServerError(false)}
					>
						There was some problem with the server. Try again...
					</Alert>
				</Snackbar>
			</Container>
		);
	}
}
Example #28
Source File: New.js    From Designer-Client with GNU General Public License v3.0 4 votes vote down vote up
export function New() {
  const theme = useTheme();
  const classes = useStyles(theme);
  const dispatch = useDispatch();
  const history = useHistory();

  const loading = useSelector(state => state.apis.loading);

  const initialForm = {
    title: "",
    nameSpace: "",
    description: "",
    dailyMaxCount: 10000,
    monthlyMaxCount: 1000000
  }

  const [form, setForm] = useState(initialForm);

  const handleChange = (e) => {
    setForm({
      ...form,
      [e.target.name]: e.target.value
    });
  }

  const onSaveButtonClick = (e) => {
    dispatch(apiActions.postNewApi(form)).then((response) => {
      if(response.error) {
        alertActions.handleError(dispatch, response.error);
        return;
      }
      history.push("/apis")
    });
  }
  return (
    <Container maxWidth='md'>
      <PageTitle text={`신규 API 추가`} align="left"/>
      <Box mt={2}>
        <FormControl className={classes.formContorrl} fullWidth={true}>
          <InputLabel width="100%" htmlFor="title-input">제목</InputLabel>
          <Input id="title-input" aria-describedby="title-helper-text" name="title" value={form.title} onChange={handleChange}/>
        </FormControl>
      </Box>
      <Box mt={2}>
        <FormControl className={classes.formContorrl} fullWidth={true}>
          <InputLabel width="100%" htmlFor="namespace-input">호출 주소 prefix</InputLabel>
          <Input id="namespace-input" aria-describedby="namespace-helper-text" name="nameSpace" value={form.nameSpace} onChange={handleChange}/>
          <FormHelperText id="namespace-helper-text">* 활용자가 API 호출시 사용하게 되는 URL 주소 정보의 일부가 됩니다. 기관 또는 API의 성향을 나타낼 수 있는 명칭을 작성해주세요.</FormHelperText>
          <FormHelperText id="namespace-helper-text">* 영문 또는 숫자로 기입 가능하며, 특수문자 _ 까지 사용 가능합니다. (띄어쓰기를 포함한 그 외의 문자 입력 불가)</FormHelperText>
        </FormControl>  
      </Box>
      <Box mt={2}>
        <FormControl className={classes.formContorrl} fullWidth={true}>
          <TextField
            id="description-input"
            label="Description"
            multiline
            rows={5}
            variant="filled"
            aria-describedby="description-helper-text"
            name="description" value={form.description} onChange={handleChange}
          />
        </FormControl>
      </Box>
      <Box mt={2}>
        <FormControl className={classes.formContorrl} fullWidth={true}>
          <InputLabel width="100%" htmlFor="maxCountPerDay-input">일별 최대 호출 건수</InputLabel>
          <Input id="maxCountPerDay-input" aria-describedby="maxCountPerDay-helper-text" name="maxCountPerDay" value={form.dailyMaxCount} onChange={handleChange}/>
        </FormControl>
      </Box>
      <Box mt={2}>
        <FormControl className={classes.formContorrl} fullWidth={true}>
          <InputLabel width="100%" htmlFor="maxCountPerMonth-input">월별 최대 호출 건수</InputLabel>
          <Input id="maxCountPerMonth-input" aria-describedby="maxCountPerMonth-helper-text" name="maxCountPerMonth" value={form.monthlyMaxCount} onChange={handleChange}/>
        </FormControl>
      </Box>
      <Box mt={2} textAlign="right">
        <Button disabled={loading} variant="contained" color="primary" onClick={onSaveButtonClick}>저장</Button>
      </Box>
    </Container>
  )
}
Example #29
Source File: KNNToolbox.js    From Otto with MIT License 4 votes vote down vote up
export default function KNNToolbox() {
  const classes = useStyles();
  const { state } = useState();
  const { model_state, model_dispatch } = useModelState();
  const [kVal, setKVal] = React.useState(model_state.knn_k);
  const [col1, setCol1] = React.useState(model_state.knn_column1_index);
  const [col2, setCol2] = React.useState(model_state.knn_column2_index);

  function onUpdatePlot() {
    model_dispatch({
      type: ModelActions.SET_KNN_COLS,
      indices: [col1, col2],
    });
    if (kVal !== model_state.knn_k) {
      model_dispatch({
        type: ModelActions.SET_KNN_K,
        k: kVal,
      });
      invokeKNN(kVal, state.sample_dataset, model_dispatch);
    }
  }

  return (
    <Grid direction="column" container style={{ marginTop: "20px" }}>
      {/* K Value */}
      <Grid item>
        <Grid direction="row" className={classes.nodesItem} container>
          <Grid item>
            <Typography className={classes.nodesLabel} gutterBottom>
              K
            </Typography>
          </Grid>
          <Grid className={classes.sliderWidth} item>
            <Slider
              value={kVal}
              valueLabelDisplay="on"
              ValueLabelComponent={ValueLabelDisplay}
              step={1}
              marks
              min={1}
              max={20}
              onChange={(event, val) => setKVal(val)}
            />
          </Grid>
        </Grid>
      </Grid>
      {/* Column 1 */}
      <Grid item className={classes.actionItem}>
        <FormControl className={classes.actionWidth}>
          <InputLabel id="demo-simple-select-label">X-Axis</InputLabel>
          <Select
            value={model_state.knn_columns.length > 0 ? col1 : ""}
            onChange={(event) => setCol1(event.target.value)}
          >
            {model_state.knn_columns.map((column, index) => (
              <MenuItem key={index} value={index}>
                {model_state.knn_columns_map[column]}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      </Grid>
      {/* Column 2 */}
      <Grid item className={classes.actionItem}>
        <FormControl className={classes.actionWidth}>
          <InputLabel id="demo-simple-select-label">Y-Axis</InputLabel>
          <Select
            value={model_state.knn_columns.length > 0 ? col2 : ""}
            onChange={(event) => setCol2(event.target.value)}
          >
            {model_state.knn_columns.map((column, index) => (
              <MenuItem key={index} value={index}>
                {model_state.knn_columns_map[column]}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      </Grid>
      <Grid item>
        <Button
          color="primary"
          className={classes.button}
          variant="outlined"
          onClick={onUpdatePlot}
        >
          {model_state.knn_k !== kVal ? "Re-Train Model" : "Update Plot"}
        </Button>
      </Grid>
    </Grid>
  );
}