@material-ui/core#FormLabel JavaScript Examples

The following examples show how to use @material-ui/core#FormLabel. 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: LabelValue.js    From akashlytics-deploy with GNU General Public License v3.0 6 votes vote down vote up
LabelValue = ({ label, value, ...rest }) => {
  const classes = useStyles();

  return (
    <Box className={clsx(classes.root)} {...rest}>
      <FormLabel className={classes.label}>{label}</FormLabel>
      <div className={classes.value}>{value}</div>
    </Box>
  );
}
Example #2
Source File: Question.js    From Quizzie with MIT License 6 votes vote down vote up
function Question(props) {
    const [value, setValue] = React.useState('none');
	const handleChange = (event) => {
		setValue(event.target.value);
	};
	return (
        <Grid item xs={10} md={8} lg={7} style={{margin: 0, padding: '2%', backgroundColor: '#111', borderBottom: '5px solid #222', minHeight: '50vh'}}>
            <FormControl style={{margin: 'auto', width:"100%"}} component="fieldset">
                <FormLabel className="label" component="legend">{props.id}</FormLabel>
                <RadioGroup aria-label="correct-choice" value={value} onChange={handleChange}>
                    <FormControlLabel value="op1" control={<Radio className="radio" />} label="Option 1" style={{margin: 0}} />
                    <FormControlLabel value="op2" control={<Radio className="radio" />} label="Option 2" style={{margin: 0}} />
                    <FormControlLabel value="op3" control={<Radio className="radio" />} label="Option 3" style={{margin: 0}} />
                    <FormControlLabel value="op4" control={<Radio className="radio" />} label="Option 4" style={{margin: 0}} />
                </RadioGroup>
            </FormControl>
        </Grid>
	)
}
Example #3
Source File: Login.js    From disposable_app with GNU General Public License v2.0 6 votes vote down vote up
render() {
      return (
        <form onSubmit={this.handleSubmit}>
        <ReCAPTCHA
            sitekey={this.props.recaptcha_key}
            ref={this.recaptchaRef}
            size="invisible"
        />
 
          <TextField 
              value={this.state.address} 
              onChange={this.handleChange}
              placeholder="(type yours)"
              inputProps={{
                style: { textAlign: "right" }
              }} 
          />
          <FormLabel>{this.props.email_domain}</FormLabel>
          <Button type="submit">Open</Button>
        </form>
      );
    }
Example #4
Source File: index.jsx    From redive_linebot with MIT License 5 votes vote down vote up
EditForm = ({ onCancel, onSubmit }) => {
  const classes = useStyles();
  const [{ data: bossData = [], loading }] = useAxios("/api/Admin/WorldBoss");
  const bossEl = useRef(null);
  const announceEl = useRef(null);
  const startTimeEl = useRef(null);
  const endTimeEl = useRef(null);

  const handleSubmit = () => {
    const [startAt, endAt] = [startTimeEl.current.value, endTimeEl.current.value];

    if (startAt >= endAt) {
      alert("請確認活動時間");
      return;
    }

    onSubmit({
      world_boss_id: parseInt(bossEl.current.value),
      announcement: announceEl.current.value,
      start_time: startAt,
      end_time: endAt,
    });
  };

  return (
    <Grid container spacing={1} component={Paper} className={classes.form}>
      {loading && <HeartbeatLoading />}
      <Grid item xs={12}>
        <Typography variant="h5">世界王活動管理</Typography>
      </Grid>
      <Grid item xs={12}>
        <FormControl fullWidth>
          <NativeSelect fullWidth inputRef={bossEl}>
            {bossData.map(boss => (
              <option key={boss.id} value={boss.id}>
                {boss.name}
              </option>
            ))}
          </NativeSelect>
          <FormHelperText>請選擇世界王來綁定活動,若無世界王,請先去新增世界王</FormHelperText>
        </FormControl>
      </Grid>
      <Grid item xs={12}>
        <TextField label="活動公告" multiline fullWidth margin="normal" inputRef={announceEl} />
      </Grid>
      <Grid item xs={6}>
        <FormControl fullWidth required margin="normal">
          <FormLabel>開始時間</FormLabel>
          <Input inputProps={{ type: "datetime-local" }} inputRef={startTimeEl} />
        </FormControl>
      </Grid>
      <Grid item xs={6}>
        <FormControl fullWidth required margin="normal">
          <FormLabel>結束時間</FormLabel>
          <Input inputProps={{ type: "datetime-local" }} inputRef={endTimeEl} />
        </FormControl>
      </Grid>
      <Grid item xs={6}>
        <Button variant="contained" color="secondary" fullWidth onClick={onCancel}>
          取消
        </Button>
      </Grid>
      <Grid item xs={6}>
        <Button variant="contained" color="primary" fullWidth onClick={handleSubmit}>
          新增
        </Button>
      </Grid>
    </Grid>
  );
}
Example #5
Source File: Settings.js    From akashlytics-deploy with GNU General Public License v3.0 4 votes vote down vote up
export function Settings(props) {
  const [isEditing, setIsEditing] = useState(false);
  const [isNodesOpen, setIsNodesOpen] = useState(false);
  const classes = useStyles();
  const { settings, setSettings, refreshNodeStatuses, isRefreshingNodeStatus } = useSettings();
  const {
    handleSubmit,
    control,
    reset,
    formState: { errors }
  } = useForm();
  const formRef = useRef();
  const { selectedNode, nodes } = settings;

  const onIsCustomNodeChange = (event) => {
    const isChecked = event.target.checked;
    const apiEndpoint = isChecked ? settings.apiEndpoint : selectedNode.api;
    const rpcEndpoint = isChecked ? settings.rpcEndpoint : selectedNode.rpc;

    reset();

    setSettings({ ...settings, isCustomNode: isChecked, apiEndpoint, rpcEndpoint }, (newSettings) => {
      refreshNodeStatuses(newSettings);
    });
  };

  const onNodeChange = (event, newNodeId) => {
    const newNode = nodes.find((n) => n.id === newNodeId);
    const apiEndpoint = newNode.api;
    const rpcEndpoint = newNode.rpc;

    setSettings({ ...settings, apiEndpoint, rpcEndpoint, selectedNode: newNode });
  };

  const onRefreshNodeStatus = async () => {
    await refreshNodeStatuses();
  };

  /**
   *  Update the custom settings
   * @param {Object} data {apiEndpoint: string, rpcEndpoint: string}
   */
  const onSubmit = (data) => {
    const customNodeUrl = new URL(data.apiEndpoint);
    setIsEditing(false);
    setSettings({ ...settings, ...data, customNode: { ...settings.customNode, id: customNodeUrl.hostname } }, (newSettings) => {
      refreshNodeStatuses(newSettings);
    });
  };

  return (
    <Box className={classes.root}>
      <Helmet title="Settings" />

      <Box className={classes.titleContainer}>
        <Typography variant="h3" className={classes.title}>
          Settings
        </Typography>
      </Box>

      <Box marginTop="1rem">
        <FormGroup>
          {!settings.isCustomNode && (
            <Box display="flex" alignItems="center">
              <FormControl>
                <Autocomplete
                  disableClearable
                  open={isNodesOpen}
                  options={nodes.map((n) => n.id)}
                  style={{ width: 300 }}
                  value={settings.selectedNode.id}
                  defaultValue={settings.selectedNode.id}
                  getOptionSelected={(option, value) => option === value}
                  onChange={onNodeChange}
                  renderInput={(params) => (
                    <ClickAwayListener onClickAway={() => setIsNodesOpen(false)}>
                      <TextField
                        {...params}
                        label="Node"
                        variant="outlined"
                        onClick={() => setIsNodesOpen((prev) => !prev)}
                        InputProps={{
                          ...params.InputProps,
                          classes: { root: clsx(classes.nodeInput, classes.inputClickable), input: classes.inputClickable },
                          endAdornment: (
                            <InputAdornment position="end">
                              <Box marginRight=".5rem" display="inline-flex">
                                <KeyboardArrowDownIcon fontSize="small" />
                              </Box>
                              <NodeStatus latency={Math.floor(selectedNode.latency)} status={selectedNode.status} />
                            </InputAdornment>
                          )
                        }}
                      />
                    </ClickAwayListener>
                  )}
                  renderOption={(option) => {
                    const node = nodes.find((n) => n.id === option);
                    return (
                      <Box display="flex" alignItems="center" justifyContent="space-between" width="100%">
                        <div>{option}</div>
                        <NodeStatus latency={Math.floor(node.latency)} status={node.status} />
                      </Box>
                    );
                  }}
                  disabled={settings.isCustomNode}
                />
              </FormControl>

              <Box marginLeft="1rem">
                <IconButton onClick={() => onRefreshNodeStatus()} aria-label="refresh" disabled={isRefreshingNodeStatus}>
                  {isRefreshingNodeStatus ? <CircularProgress size="1.5rem" /> : <RefreshIcon />}
                </IconButton>
              </Box>
            </Box>
          )}

          <FormControlLabel
            className={classes.switch}
            control={<Switch checked={!!settings.isCustomNode} onChange={onIsCustomNodeChange} color="primary" />}
            label="Custom node"
          />
        </FormGroup>
      </Box>

      {settings.isCustomNode && (
        <form className={classes.form} onSubmit={handleSubmit(onSubmit)} ref={formRef}>
          <div className={classes.fieldRow}>
            <FormLabel className={classes.formLabel}>Api Endpoint:</FormLabel>

            {isEditing ? (
              <FormControl error={!errors.apiEndpoint} className={classes.formControl}>
                <Controller
                  control={control}
                  name="apiEndpoint"
                  rules={{
                    required: true,
                    validate: (v) => isUrl(v)
                  }}
                  defaultValue={settings.apiEndpoint}
                  render={({ fieldState, field }) => {
                    const helperText = fieldState.error?.type === "validate" ? "Url is invalid." : "Api endpoint is required.";

                    return (
                      <TextField
                        {...field}
                        type="text"
                        variant="outlined"
                        error={!!fieldState.invalid}
                        helperText={fieldState.invalid && helperText}
                        className={classes.formValue}
                      />
                    );
                  }}
                />
              </FormControl>
            ) : (
              <Typography variant="body1" className={classes.formValue}>
                {settings.apiEndpoint}
              </Typography>
            )}
          </div>

          <div className={classes.fieldRow}>
            <FormLabel className={classes.formLabel}>Rpc Endpoint:</FormLabel>

            {isEditing ? (
              <FormControl error={!errors.apiEndpoint} className={classes.formControl}>
                <Controller
                  control={control}
                  name="rpcEndpoint"
                  rules={{
                    required: true,
                    validate: (v) => isUrl(v)
                  }}
                  defaultValue={settings.rpcEndpoint}
                  render={({ fieldState, field }) => {
                    const helperText = fieldState.error?.type === "validate" ? "Url is invalid." : "Rpc endpoint is required.";

                    return (
                      <TextField
                        {...field}
                        type="text"
                        variant="outlined"
                        error={!!fieldState.invalid}
                        helperText={fieldState.invalid && helperText}
                        className={classes.formValue}
                      />
                    );
                  }}
                />
              </FormControl>
            ) : (
              <Typography variant="body1" className={classes.formValue}>
                {settings.rpcEndpoint}
              </Typography>
            )}
          </div>

          <Box paddingTop="1rem">
            {!isEditing && (
              <Button variant="contained" color="primary" onClick={() => setIsEditing(!isEditing)}>
                Edit
              </Button>
            )}

            {isEditing && (
              <>
                <Button
                  variant="contained"
                  onClick={() => {
                    reset(null, { keepDefaultValues: true });
                    setIsEditing(false);
                  }}
                >
                  Cancel
                </Button>
                <Button
                  variant="contained"
                  color="primary"
                  type="submit"
                  className={classes.submitButton}
                  onClick={() => formRef.current.dispatchEvent(new Event("submit"))}
                >
                  Submit
                </Button>
              </>
            )}
          </Box>
        </form>
      )}
    </Box>
  );
}
Example #6
Source File: HdPath.js    From akashlytics-deploy with GNU General Public License v3.0 4 votes vote down vote up
HdPath = ({ onChange }) => {
  const [isShowingAdvanced, setIsShowingAdvanced] = useState(false);
  const [account, setAccount] = useState(0);
  const [change, setChange] = useState(0);
  const [addressIndex, setAddressIndex] = useState(0);
  const classes = useStyles();

  const onAdvancedClick = () => {
    setIsShowingAdvanced((prev) => {
      const newVal = !prev;

      // Reset values on close
      if (!newVal) {
        setAccount(0);
        setChange(0);
        setAddressIndex(0);
        onChange(0, 0, 0);
      }

      return newVal;
    });
  };

  return (
    <div className={classes.root}>
      <Box textAlign="center" marginBottom="1rem">
        <Button onClick={onAdvancedClick} size="small" color="primary">
          Advanced
        </Button>
      </Box>

      {isShowingAdvanced && (
        <Box>
          <FormLabel>HD Derivation Path</FormLabel>
          <Box display="flex" alignItems="baseline">
            <div>
              <Typography variant="body2">m/44'/···'/</Typography>
            </div>
            <TextField
              value={account}
              onChange={(ev) => {
                const _value = ev.target.value;
                setAccount(_value);
                onChange(_value, change, addressIndex);
              }}
              type="number"
              variant="outlined"
              classes={{ root: classes.inputRoot }}
              InputProps={{
                classes: { input: classes.input }
              }}
              inputProps={{
                min: 0,
                step: 1
              }}
              size="medium"
            />
            <div>
              <Typography variant="body2">'/</Typography>
            </div>
            <TextField
              value={change}
              onChange={(ev) => {
                const _value = ev.target.value;
                setChange(_value);
                onChange(account, _value, addressIndex);
              }}
              type="number"
              variant="outlined"
              classes={{ root: classes.inputRoot }}
              InputProps={{
                classes: { input: classes.input }
              }}
              inputProps={{
                min: 0,
                max: 1,
                step: 1
              }}
              size="medium"
            />
            <div>
              <Typography variant="body2">/</Typography>
            </div>
            <TextField
              value={addressIndex}
              onChange={(ev) => {
                const _value = ev.target.value;
                setAddressIndex(_value);
                onChange(account, change, _value);
              }}
              type="number"
              variant="outlined"
              classes={{ root: classes.inputRoot }}
              InputProps={{
                classes: { input: classes.input }
              }}
              inputProps={{
                min: 0,
                step: 1
              }}
              size="medium"
            />
          </Box>
        </Box>
      )}
    </div>
  );
}
Example #7
Source File: Quiz.js    From Quizzie with MIT License 4 votes vote down vote up
function Quiz(props) {
	const [quizId, setQuizId] = useState(null);
	const [currentStep, setStep] = useState(1);

	const [loading, setLoading] = useState(true);
	const [allQuestions, setQuestions] = useState([]);
	const [currentQuestion, setCurrentQuestion] = useState(0);
	const [currentAns, setCurrentAns] = useState(null);

	const [duration, setDuration] = useState(-1);
	const [startTime, setStartTime] = useState(-1);
	const [timeRemaining, setTimeRemaining] = useState("");
	const [timeUp, setTimeUp] = useState(false);

	const [tabChange, setTabChange] = useState(false);

	const [allChosenAns, setAllAns] = useState(null);
	const [redirect, setRedirect] = useState(false);
	const [resultRedirect, setResultRedirect] = useState(false);

	const [submitLoading, setSubmitLoading] = useState(false);

	const [confirmModal, setConfirmModal] = useState(false);
	const [empty, setEmpty] = useState(false);
	const [restartStatus, setRestartStatus] = useState(-1);

	const pageVisible = usePageVisibility();
	const { executeRecaptcha } = useGoogleReCaptcha();

	const submitQuiz = async () => {
		setSubmitLoading(true);
		let token = localStorage.getItem("authToken");
		let url = "https://quizzie-api.herokuapp.com/quiz/check";

		let captcha = await executeRecaptcha("submit_token");

		let data = {
			quizId: quizId,
			questions: allChosenAns,
			timeStarted: props.location.state.timeStarted,
			timeEnded: Date.now(),
			captcha: captcha,
		};

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

	const onCloseHandle = () => {
		setConfirmModal(false);
	};

	const handleSubmitBtn = () => {
		setConfirmModal(true);
	};

	const handleSubmit = (event) => {
		submitQuiz();
	};
	const timesUp = async () => {
		setLoading(true);
		setTimeUp(true);
		let token = localStorage.getItem("authToken");
		let url = "https://quizzie-api.herokuapp.com/quiz/finish";

		let data = {
			quizId: quizId,
		};

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

	const _next = () => {
		let currQues = currentQuestion + 1;
		setStep(currentStep + 1);
		setCurrentQuestion(currentQuestion + 1);
		setCurrentAns(allChosenAns[currQues].selectedOption);
	};
	const _prev = () => {
		let currQues = currentQuestion - 1;
		setStep(currentStep - 1);
		setCurrentQuestion(currentQuestion - 1);
		setCurrentAns(allChosenAns[currQues].selectedOption);
	};
	const previousButton = () => {
		if (currentStep !== 1) {
			return (
				<button className="quiz-btn prev-button" onClick={_prev}>
					<p>Previous</p>
				</button>
			);
		}
		return null;
	};

	const nextButton = () => {
		if (currentStep < allQuestions.length) {
			return (
				<button className="quiz-btn next-button" onClick={_next}>
					<p>Next</p>
				</button>
			);
		} else if (currentStep === allQuestions.length) {
			return (
				<button
					className="quiz-btn submit-button"
					onClick={handleSubmitBtn}
				>
					<p>Submit</p>
				</button>
			);
		}
		return null;
	};

	const handleOptionChange = (event) => {
		setCurrentAns(event.target.value);

		let newState = allChosenAns;
		newState[currentQuestion].selectedOption = event.target.value;

		setAllAns(newState);
	};

	const setupQuiz = (questions) => {
		let questionsData = [];
		let answerData = [];

		if (questions.length === 0) {
			setEmpty(true);
			setRedirect(true);
			return;
		}

		questions.map((question) => {
			let questionObj = {
				q_id: question.questionId,
				text: question.description,
				options: question.options,
			};
			questionsData.push(questionObj);

			let ansObj = {
				quesId: question.questionId,
				selectedOption: null,
			};

			answerData.push(ansObj);
		});

		setQuestions(questionsData);
		setAllAns(answerData);

		setLoading(false);
	};

	useEffect(() => {
		if (!pageVisible) {
			setTabChange(true);
			setRedirect(true);
			return;
		}
	}, [pageVisible]);

	useEffect(() => {
		if (restartStatus !== 1) {
			let endTime = Number(startTime) + duration * 60 * 1000;
			if (
				!loading &&
				endTime > 0 &&
				Number(endTime) < Number(Date.now())
			) {
				timesUp();
				return;
			} else {
				setTimeout(() => {
					setTimeRemaining(
						countdown(
							new Date(),
							new Date(Number(endTime)),
							countdown.MINUTES | countdown.SECONDS
						).toString()
					);
				}, 1000);
			}
		}
	});

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

		if (props.location.state === undefined) {
			setRedirect(true);
			return;
		} else {
			setQuizId(props.location.state.id);
			setDuration(props.location.state.duration);
			setStartTime(props.location.state.start);
			setQuestions(props.location.state.questions);
			setupQuiz(props.location.state.questions);
			setRestartStatus(props.location.state.restartStatus);
		}
	}, []);

	if (redirect) {
		return (
			<Redirect
				to={{
					pathname: "/dashboard",
					state: {
						blocked: tabChange,
						timeUp: timeUp,
						emptyQuiz: empty,
					},
				}}
			/>
		);
	} else if (resultRedirect) {
		return <Redirect to={`/results/${quizId}`} />;
	} else if (submitLoading) {
		return <SubmitLoading />;
	} else {
		return loading ? (
			<Loading />
		) : (
			<div className="quiz-page">
				<Grid container xs={12} spacing={5} className="quiz-container">
					<Grid item xs={10} md={8} lg={7} className="q-count">
						<h2 style={{ padding: 0 }}>
							QUESTION {currentStep} OF {allQuestions.length}
						</h2>
					</Grid>
					<Grid item xs={10} md={8} lg={7} className="timer">
						<p style={{ margin: 0 }}>
							Time Remaining{" "}
							<h2 className="rem-time-display">
								{restartStatus !== 1
									? timeRemaining
									: "Until organizer closes the quiz"}
							</h2>
						</p>
					</Grid>
					<Grid
						item
						xs={10}
						md={8}
						lg={7}
						style={{
							margin: 0,
							padding: "2%",
							borderBottom: "3px solid #222",
							minHeight: "30vh",
						}}
					>
						<FormControl
							style={{ margin: "auto", width: "100%" }}
							component="fieldset"
						>
							<FormLabel className="label" component="legend">
								<p className="question">
									{allQuestions[currentQuestion].text}
								</p>
							</FormLabel>
							<RadioGroup
								aria-label="correct-choice"
								value={currentAns}
								onChange={handleOptionChange}
							>
								{allQuestions[currentQuestion].options.map(
									(option) => {
										return (
											<FormControlLabel
												key={option._id}
												value={option.text}
												control={
													<Radio className="radio" />
												}
												label={option.text}
												style={{ margin: 0 }}
											/>
										);
									}
								)}
							</RadioGroup>
						</FormControl>
					</Grid>
					<Grid item xs={10} md={8} lg={7} className="button">
						<Grid item xs={6} className="button">
							{previousButton()}
						</Grid>
						<Grid item xs={6} className="button">
							{nextButton()}
						</Grid>
					</Grid>
				</Grid>

				<Dialog
					open={confirmModal}
					onClose={onCloseHandle}
					aria-labelledby="form-dialog-title"
					PaperProps={{
						style: {
							backgroundColor: "white",
							color: "#333",
							minWidth: "10%",
						},
					}}
				>
					<DialogTitle>
						Are you sure you want to submit the quiz?
					</DialogTitle>
					<div className="btn-div">
						<Button
							className="logout-btn m-right"
							onClick={handleSubmit}
						>
							Yes
						</Button>
						<Button
							className="cancel-btn m-left"
							onClick={onCloseHandle}
						>
							No
						</Button>
					</div>
				</Dialog>
			</div>
		);
	}
}
Example #8
Source File: CargoShip.jsx    From archeage-tools with The Unlicense 4 votes vote down vote up
render() {
    const { alerts, setAlert, speak, setSpeak, servers, server: serverId, mobile, openDialog } = this.props;
    const { open, setup, stepIndex, endTime, shipPosition, menu, updated } = this.state;
    const now = moment();
    let eventStepTime = moment(endTime);
    const step = CARGO_SCHEDULE[stepIndex];

    const server = servers[serverId];
    const serverName = pathOr('???', ['name'])(server);

    return [
      <Paper className="cargo-ship event-list" key="cargo-timer">
        <AppBar position="static">
          <Toolbar variant="dense">
            <Icon><img src={'/images/event_type/exploration.png'} alt="Cargo Ship" /></Icon>
            <Typography variant="subtitle1" className="title-text">[{serverName}] Cargo Ship</Typography>
            <IfPerm permission={`cargo.${serverName.toLowerCase()}`}>
              <Tooltip title={`Edit ${serverName} Timer`}>
                <IconButton onClick={this.toggleDialog} color="inherit">
                  <EditIcon />
                </IconButton>
              </Tooltip>
            </IfPerm>
            <Tooltip title="Change Server">
              <IconButton onClick={() => openDialog(DIALOG_MY_GAME, SERVER)} color="inherit">
                <HomeIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="Configure alerts">
              <IconButton
                onClick={this.handleOpenMenu}
                className="super-btn"
              >
                <NotificationsIcon
                  className={cn({ 'notif-fade': alerts.length === 0 })}
                  color="inherit"
                />
                {alerts.length > 0 &&
                <Typography className="super-text" color="primary">{alerts.length}</Typography>}
              </IconButton>
            </Tooltip>
          </Toolbar>
        </AppBar>
        <div className="cargo-slider">
          <div className="cargo-rail" />
          <Tooltip title="Solis Headlands Trade Outlet">
            <div className="cargo-icon austera" />
          </Tooltip>
          <Tooltip title="Two Crowns Trade Outlet">
            <div className="cargo-icon two-crowns" />
          </Tooltip>
          <div
            className={cn('cargo-icon ship', { moving: !step.port, reverse: step.reverse })}
            style={{ [step.reverse ? 'left' : 'right']: `${(shipPosition / step.duration) * 100}%` }}
          />
        </div>
        <div className="cargo-text">
          {!server &&
          <Typography>Select a server to see the cargo ship location.</Typography>}
          {server && !updated &&
          <Typography>The cargo ship has not been updated since the last maintenance.</Typography>}
          {server && updated &&
          <>
            <Typography>Cargo ship is {step.text}.</Typography>
            <br />
            <Table size="small" stickyHeader className="timer-table">
              <TableHead>
                <TableRow>
                  <TableCell>
                    Event
                  </TableCell>
                  <TableCell>
                    Time
                  </TableCell>
                  <TableCell align="right">
                    Countdown
                  </TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {Array.from(Array(CARGO_SCHEDULE.length).keys()).map((_, i) => {
                  const index = getNextIndex(stepIndex + i - 1);
                  const step = CARGO_SCHEDULE[index];
                  if (i > 0) {
                    eventStepTime.add(step.duration, 'seconds');
                  }
                  return (
                    <TableRow key={`cargo-${i}`}>
                      <TableCell>{step.next}</TableCell>
                      <TableCell>{eventStepTime.format('h:mm A')}</TableCell>
                      <TableCell align="right">{hhmmssFromDate(eventStepTime.diff(now))}</TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </>}
        </div>
      </Paper>,
      <Dialog
        open={open}
        key="cargo-settings"
        onClose={this.toggleDialog}
        maxWidth="sm"
      >
        <AppBar position="static">
          <Toolbar variant="dense">
            <Typography variant="subtitle1" className="title-text">Cargo Ship Setup</Typography>
            <Tooltip title="Close">
              <IconButton onClick={this.toggleDialog}>
                <CloseIcon />
              </IconButton>
            </Tooltip>
          </Toolbar>
        </AppBar>
        <DialogContent>
          <Typography>To setup the timer, the ship must currently be docked at a port.</Typography>
          <br />
          <FormControl component="fieldset">
            <FormLabel component="legend">What port is the ship at?</FormLabel>
            <RadioGroup name="port" value={Number.parseInt(setup.port)} onChange={this.handleSetupChange('port')} row>
              <FormControlLabel
                control={<Radio color="primary" />}
                label="Solis Headlands"
                value={ZONE.SOLIS_HEADLANDS}
              />
              <FormControlLabel
                control={<Radio color="primary" />}
                label="Two Crowns"
                value={ZONE.TWO_CROWNS}
              />
            </RadioGroup>
          </FormControl>
          <FormControl component="fieldset">
            <FormLabel component="legend">What is the remaining time on the &quot;Cargo Ship
              Anchored&quot; buff?</FormLabel>
            <div className="duration-pick">
              <Input
                id="mm"
                placeholder="20"
                endAdornment="m"
                inputProps={{
                  maxLength: 2,
                  ref: this.mm,
                }}
                value={setup.mm}
                onChange={this.handleTimeChange('mm')}
                onKeyPress={this.handleEnter}
              />
              <Input
                id="ss"
                placeholder="00"
                endAdornment="s"
                inputProps={{
                  maxLength: 2,
                  ref: this.ss,
                }}
                value={setup.ss}
                onChange={this.handleTimeChange('ss')}
                onKeyPress={this.handleEnter}
              />
            </div>
          </FormControl>
          <FormControl component="fieldset">
            <FormControlLabel
              control={<Checkbox color="primary" />}
              label="Don't Update Sibling Realms"
              checked={setup.noLinkedUpdate}
              onChange={this.handleNoLink}
            />
          </FormControl>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={this.submitSetup}
            color="primary"
            disabled={!setup.port || (String(setup.mm).length === 0 && String(setup.ss).length === 0)}
          >
            Update
          </Button>
        </DialogActions>
      </Dialog>,
      <Menu
        id="alert-menu"
        anchorEl={menu}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'center',
        }}
        getContentAnchorEl={null}
        open={Boolean(menu)}
        onClose={this.handleCloseMenu}
        className="alert-menu"
        autoFocus={false}
        key="alert-menu"
        variant="menu"
      >
        <ListItem tabIndex={null} dense={!mobile}>
          <ListItemText>Alert Types:</ListItemText>
        </ListItem>
        <MenuItem disabled dense={!mobile}>
          <ListItemIcon>
            <CheckBoxIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>Audio Cue</ListItemText>
        </MenuItem>
        <MenuItem
          onClick={setSpeak(CARGO_ID, !speak)}
          dense={!mobile}
          disabled={!CAN_SPEAK}
          divider
        >
          <ListItemIcon>
            {speak
              ? <CheckBoxIcon fontSize="small" color="primary" />
              : <CheckBoxOutlineBlankIcon fontSize="small" />}
          </ListItemIcon>
          <ListItemText>Audio Message</ListItemText>
        </MenuItem>
        <ListItem tabIndex={null} dense={!mobile}>
          <ListItemText>Alert Times:</ListItemText>
          <ListItemSecondaryAction>
            <Tooltip title="Clear all">
                <span>
                  <IconButton size="small" onClick={setAlert(CARGO_ID, '')} disabled={alerts.length === 0}>
                    <CloseIcon fontSize="small" />
                  </IconButton>
                </span>
            </Tooltip>
          </ListItemSecondaryAction>
        </ListItem>
        {Object.entries(CARGO_ALERTS).map(([key, option]) => (
          <MenuItem
            dense={!mobile}
            onClick={setAlert(CARGO_ID, key)}
            key={`alert-opt-${randomString(16)}-${key}`}
          >
            <ListItemIcon>
              {alerts.includes(key)
                ? <CheckBoxIcon fontSize="small" color="primary" />
                : <CheckBoxOutlineBlankIcon fontSize="small" />}
            </ListItemIcon>
            <ListItemText>{option.name}</ListItemText>
          </MenuItem>
        ))}
      </Menu>,
    ];
  }
Example #9
Source File: AuthWrapper.jsx    From Edlib with GNU General Public License v3.0 4 votes vote down vote up
AuthWrapper = ({ children }) => {
    const [jwtToken, setJwtToken] = React.useState(null);

    const [firstName, setFirstName] = React.useState(() => {
        const stored = store.get('firstName');
        return stored ? stored : '';
    });
    const [lastName, setLastName] = React.useState(() => {
        const stored = store.get('lastName');
        return stored ? stored : '';
    });
    const [email, setEmail] = React.useState(() => {
        const stored = store.get('email');
        return stored ? stored : '';
    });
    const [id, setId] = React.useState(() => {
        const stored = store.get('userId');
        return stored ? stored : '';
    });
    const [language, setLanguage] = React.useState(() => {
        const stored = store.get('language');
        return stored ? stored : 'nb';
    });

    React.useEffect(() => {
        store.set('firstName', firstName);
        store.set('lastName', lastName);
        store.set('email', email);
        store.set('userId', id);
        store.set('language', language);
    }, [firstName, lastName, email, id, language]);

    if (!jwtToken) {
        return (
            <div style={{ maxWidth: 500 }}>
                <div>
                    <TextField
                        label="First name"
                        value={firstName}
                        onChange={(e) => setFirstName(e.target.value)}
                        margin="normal"
                    />
                    <TextField
                        label="Last name"
                        value={lastName}
                        onChange={(e) => setLastName(e.target.value)}
                        margin="normal"
                    />
                </div>
                <div>
                    <TextField
                        label="Email"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        margin="normal"
                        fullWidth
                    />
                    <TextField
                        label="User ID"
                        value={id}
                        onChange={(e) => setId(e.target.value)}
                        margin="normal"
                        fullWidth
                    />
                </div>
                <div>
                    <FormControl component="fieldset">
                        <FormLabel component="legend">Language</FormLabel>
                        <RadioGroup
                            name="language"
                            value={language}
                            onChange={(e) => setLanguage(e.target.value)}
                        >
                            <FormControlLabel
                                value="nb"
                                control={<Radio />}
                                label="Norsk"
                            />
                            <FormControlLabel
                                value="en"
                                control={<Radio />}
                                label="English"
                            />
                        </RadioGroup>
                    </FormControl>
                </div>
                <Button
                    color="primary"
                    variant="contained"
                    onClick={() => {
                        setJwtToken(
                            sign(
                                {
                                    exp:
                                        Math.floor(Date.now() / 1000) + 60 * 60,
                                    data: {
                                        isFakeToken: true,
                                        user: {
                                            firstName:
                                                firstName.length !== 0
                                                    ? firstName
                                                    : null,
                                            lastName:
                                                lastName.length !== 0
                                                    ? lastName
                                                    : null,
                                            email:
                                                email.length !== 0
                                                    ? email
                                                    : null,
                                            id,
                                            isAdmin: true,
                                        },
                                    },
                                    iss: 'fake',
                                },
                                'anything'
                            )
                        );
                    }}
                >
                    Start new session
                </Button>
            </div>
        );
    }

    return children({
        getJwt: async () => {
            if (jwtToken && isTokenExpired(jwtToken)) {
                setJwtToken(null);
                return null;
            }

            return jwtToken;
        },
        getLanguage: () => {
            return language;
        },
    });
}
Example #10
Source File: MockLogin.jsx    From Edlib with GNU General Public License v3.0 4 votes vote down vote up
MockLogin = () => {
    const history = useHistory();
    const [firstName, setFirstName] = React.useState(() => {
        const stored = store.get('firstName');
        return stored ? stored : '';
    });
    const [lastName, setLastName] = React.useState(() => {
        const stored = store.get('lastName');
        return stored ? stored : '';
    });
    const [email, setEmail] = React.useState(() => {
        const stored = store.get('email');
        return stored ? stored : '';
    });
    const [id, setId] = React.useState(() => {
        const stored = store.get('userId');
        return stored ? stored : '';
    });
    const [language, setLanguage] = React.useState(() => {
        const stored = store.get('language');
        return stored ? stored : 'nb';
    });

    React.useEffect(() => {
        store.set('firstName', firstName);
        store.set('lastName', lastName);
        store.set('email', email);
        store.set('userId', id);
        store.set('language', language);
    }, [firstName, lastName, email, id, language]);

    return (
        <div style={{ maxWidth: 500 }}>
            <div>
                <TextField
                    label="First name"
                    value={firstName}
                    onChange={(e) => setFirstName(e.target.value)}
                    margin="normal"
                />
                <TextField
                    label="Last name"
                    value={lastName}
                    onChange={(e) => setLastName(e.target.value)}
                    margin="normal"
                />
            </div>
            <div>
                <TextField
                    label="Email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    margin="normal"
                    fullWidth
                />
                <TextField
                    label="User ID"
                    value={id}
                    onChange={(e) => setId(e.target.value)}
                    margin="normal"
                    fullWidth
                />
            </div>
            <div>
                <FormControl component="fieldset">
                    <FormLabel component="legend">Language</FormLabel>
                    <RadioGroup
                        name="language"
                        value={language}
                        onChange={(e) => setLanguage(e.target.value)}
                    >
                        <FormControlLabel
                            value="nb"
                            control={<Radio />}
                            label="Norsk"
                        />
                        <FormControlLabel
                            value="en"
                            control={<Radio />}
                            label="English"
                        />
                    </RadioGroup>
                </FormControl>
            </div>
            <Button
                color="primary"
                variant="contained"
                onClick={() => {
                    history.push(
                        `/login/callback?jwt=${sign(
                            {
                                exp: Math.floor(Date.now() / 1000) + 60 * 60,
                                data: {
                                    isFakeToken: true,
                                    user: {
                                        firstName:
                                            firstName.length !== 0
                                                ? firstName
                                                : null,
                                        lastName:
                                            lastName.length !== 0
                                                ? lastName
                                                : null,
                                        email:
                                            email.length !== 0 ? email : null,
                                        id,
                                        isAdmin: true,
                                    },
                                },
                                iss: 'fake',
                            },
                            'anything'
                        )}`
                    );
                }}
            >
                Start new session
            </Button>
        </div>
    );
}
Example #11
Source File: Register.js    From inventory-management-web with MIT License 4 votes vote down vote up
Register = () => {
  // Use custom hook for form state management
  const {
    handleChange,
    handleSubmit,
    error,
    invalidCred,
    values,
    showConfirmPassword,
    showPassword,
    toggleShowPassword,
    toggleShowconfirmPassword,
    isLoading,
  } = useForm();

  const classes = useStyles({ invalid: invalidCred });

  return (
    <>
      {isLoading ? <Spinner /> : null}
      <Paper className={classes.paper}>
        <Typography variant='h4' className={classes.heading}>
          Add New Employee
        </Typography>
        <Typography
          variant='h6'
          color='error'
          className={classes.invalid}
          gutterBottom
        >
          {invalidCred}
        </Typography>
        <form
          noValidate
          onSubmit={handleSubmit}
          autoComplete='off'
          className={classes.gridContainer}
        >
          <Divider />
          <Typography variant='h5' className={classes.formHeading}>
            Account
          </Typography>
          <div className={classes.form}>
            <TextField
              required
              variant='filled'
              id='last-name-input'
              name='firstName'
              label='First Name'
              value={values.firstName}
              onChange={handleChange}
              error={!(error.firstName === ' ')}
              helperText={error.firstName}
            />
            <TextField
              required
              variant='filled'
              id='first-name-input'
              name='lastName'
              label='Last Name'
              value={values.lastName}
              onChange={handleChange}
              error={!(error.lastName === ' ')}
              helperText={error.lastName}
            />
            <TextField
              required
              variant='filled'
              id='email-input'
              name='email'
              type='email'
              label='Email'
              value={values.email}
              onChange={handleChange}
              error={!(error.email === ' ')}
              helperText={error.email}
            />
            <TextField
              required
              variant='filled'
              id='password-input'
              name='password'
              type={showPassword ? 'text' : 'password'}
              label='Password'
              value={values.password}
              onChange={handleChange}
              error={!(error.password === ' ')}
              helperText={error.password}
              InputProps={{
                endAdornment: (
                  <InputAdornment position='end'>
                    <IconButton onClick={toggleShowPassword} tabIndex='-1'>
                      {showPassword ? <Visibility /> : <VisibilityOff />}
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
            <TextField
              required
              variant='filled'
              id='confirm-password-input'
              name='confirmPassword'
              type={showConfirmPassword ? 'text' : 'password'}
              label='Confirm Password'
              value={values.confirmPassword}
              onChange={handleChange}
              error={!(error.confirmPassword === ' ')}
              helperText={error.confirmPassword}
              InputProps={{
                endAdornment: (
                  <InputAdornment position='end'>
                    <IconButton
                      onClick={toggleShowconfirmPassword}
                      tabIndex='-1'
                    >
                      {showConfirmPassword ? <Visibility /> : <VisibilityOff />}
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
            <TextField
              required
              variant='filled'
              id='gender-input'
              name='gender'
              select
              label='Employee Gender'
              value={values.gender}
              onChange={handleChange}
              error={!(error.gender === ' ')}
              helperText={error.gender}
            >
              {['Male', 'Female', 'Other'].map((option, index) => (
                <MenuItem key={option} value={['M', 'F', 'Other'][index]}>
                  {option}
                </MenuItem>
              ))}
            </TextField>
            <TextField
              required
              variant='filled'
              id='age-input'
              name='age'
              type='number'
              label='Employee Age'
              InputProps={{
                inputProps: {
                  min: 0,
                },
              }}
              value={values.age}
              onChange={handleChange}
              error={!(error.age === ' ')}
              helperText={error.age}
            />
            <FormControl component='fieldset'>
              <FormLabel component='legend'>Type</FormLabel>
              <RadioGroup
                name='isStaff'
                value={values.isStaff}
                onChange={handleChange}
                className={classes.radio}
              >
                <FormControlLabel
                  value='true'
                  control={<Radio />}
                  label='Manager'
                />
                <FormControlLabel
                  value='false'
                  control={<Radio />}
                  label='Employee'
                />
              </RadioGroup>
            </FormControl>
          </div>
          <Button
            type='submit'
            color='primary'
            variant='contained'
            className={classes.button}
            onClick={handleSubmit}
          >
            Register
          </Button>
        </form>
      </Paper>
    </>
  );
}
Example #12
Source File: UpdateEmployeeForm.js    From inventory-management-web with MIT License 4 votes vote down vote up
UpdateEmployee = () => {
  // get state from location
  const location = useLocation();
  const { firstName, lastName, age, isStaff, email } = location.state;
  // Use custom hook for form state management
  const {
    handleChange,
    handleSubmit,
    error,
    invalidCred,
    values,
    isLoading,
  } = useForm({ firstName, lastName, age, isStaff, email });

  const classes = useStyles({ invalid: invalidCred });

  return (
    <>
      {isLoading ? <Spinner /> : null}
      <Paper className={classes.paper}>
        <Typography variant='h4' className={classes.heading}>
          User Update
        </Typography>
        <Typography
          variant='h6'
          color='error'
          className={classes.invalid}
          gutterBottom
        >
          {invalidCred}
        </Typography>
        <form
          noValidate
          onSubmit={handleSubmit}
          autoComplete='off'
          className={classes.gridContainer}
        >
          <Divider />
          <Typography variant='h5' className={classes.formHeading}>
            Account
          </Typography>
          <div className={classes.form}>
            <TextField
              disabled
              variant='filled'
              id='email-input'
              name='email'
              type='email'
              label='Email'
              value={email}
              onChange={handleChange}
              helperText={' '}
            />
            <TextField
              required
              variant='filled'
              id='last-name-input'
              name='firstName'
              label='First Name'
              value={values.firstName}
              onChange={handleChange}
              error={!(error.firstName === ' ')}
              helperText={error.firstName}
            />
            <TextField
              required
              variant='filled'
              id='first-name-input'
              name='lastName'
              label='Last Name'
              value={values.lastName}
              onChange={handleChange}
              error={!(error.lastName === ' ')}
              helperText={error.lastName}
            />
            <TextField
              required
              variant='filled'
              id='age-input'
              name='age'
              type='number'
              label='Employee Age'
              InputProps={{
                inputProps: {
                  min: 0,
                },
              }}
              value={values.age}
              onChange={handleChange}
              error={!(error.age === ' ')}
              helperText={error.age}
            />
            <FormControl component='fieldset'>
              <FormLabel component='legend'>Type</FormLabel>
              <RadioGroup
                name='isStaff'
                value={values.isStaff}
                onChange={handleChange}
                className={classes.radio}
              >
                <FormControlLabel
                  value='True'
                  control={<Radio />}
                  label='Manager'
                />
                <FormControlLabel
                  value='False'
                  control={<Radio />}
                  label='Employee'
                />
              </RadioGroup>
            </FormControl>
          </div>
          <Button
            type='submit'
            color='primary'
            variant='contained'
            className={classes.button}
            onClick={handleSubmit}
          >
            Update
          </Button>
        </form>
      </Paper>
    </>
  );
}
Example #13
Source File: UpdateProductForm.js    From inventory-management-web with MIT License 4 votes vote down vote up
UpdateProduct = () => {
  // get state from location
  const location = useLocation();
  const {
    name,
    sellingPrice,
    id,
    loose,
    upperLimit,
    lowerLimit,
  } = location.state;
  // Use custom hook for form state management
  const { handleChange, handleSubmit, error, values, isLoading } = useForm({
    name,
    sellingPrice,
    loose,
    id,
    upperLimit,
    lowerLimit,
  });

  const classes = useStyles();

  return (
    <>
      {isLoading ? <Spinner /> : null}
      <Paper className={classes.paper}>
        <Typography variant='h4' className={classes.heading}>
          Update Product
        </Typography>
        <form
          noValidate
          onSubmit={handleSubmit}
          autoComplete='off'
          className={classes.gridContainer}
        >
          <Divider />
          <Typography variant='h5' className={classes.formHeading}>
            Product
          </Typography>
          <div className={classes.form}>
            <TextField
              required
              variant='filled'
              id='name-input'
              name='name'
              label='Name'
              value={values.name}
              onChange={handleChange}
              error={!(error.name === ' ')}
              helperText={error.name}
            />
            <TextField
              required
              variant='filled'
              id='sellingPrice-input'
              type='number'
              name='sellingPrice'
              label='Selling Price'
              InputProps={{
                inputProps: {
                  min: 0,
                },
              }}
              value={values.sellingPrice}
              onChange={handleChange}
              error={!(error.sellingPrice === ' ')}
              helperText={error.sellingPrice}
            />
            <TextField
              variant='filled'
              id='upperLimit-input'
              type='number'
              name='upperLimit'
              label='Recommended Limit'
              InputProps={{
                inputProps: {
                  min: 0,
                },
              }}
              value={values.upperLimit}
              onChange={handleChange}
              error={!(error.upperLimit === ' ')}
              helperText={error.upperLimit}
            />
            <TextField
              variant='filled'
              id='lowerLimit-input'
              type='number'
              name='lowerLimit'
              label='Critical Limit'
              InputProps={{
                inputProps: {
                  min: 0,
                },
              }}
              value={values.lowerLimit}
              onChange={handleChange}
              error={!(error.lowerLimit === ' ')}
              helperText={error.lowerLimit}
            />
            <FormControl component='fieldset'>
              <FormLabel component='legend'>Type</FormLabel>
              <RadioGroup
                name='loose'
                value={values.loose}
                onChange={handleChange}
                className={classes.radio}
              >
                <FormControlLabel
                  value='true'
                  control={<Radio />}
                  label='Loose'
                />
                <FormControlLabel
                  value='false'
                  control={<Radio />}
                  label='Packed'
                />
              </RadioGroup>
            </FormControl>
          </div>
          <Button
            type='submit'
            color='primary'
            variant='contained'
            className={classes.button}
            onClick={handleSubmit}
          >
            Update
          </Button>
        </form>
      </Paper>
    </>
  );
}
Example #14
Source File: App.js    From cloud-dapr-demo with MIT License 4 votes vote down vote up
export default function App() {
  const classes = useStyles();
  const [activeStep, setActiveStep] = useState(0);
  const [food, setFood] = useState('');
  const [drink, setDrink] = useState('');
  const [loading, setLoading] = useState(false);
  const [orderId, setOrderId] = useState(null);
  const [status, setStatus] = useState(null);

  const steps = getSteps();

  function submitOrder() {
    setLoading(true);
    axios.post(`${baseUrl}/order`, {
      food, drink
    }).then((res) => {
      setOrderId(res.data.id);
    }).finally(() => setLoading(false));
  }

  useEffect(() => {
    if (orderId) {
      pollStatus(orderId);
    }
  }, [orderId]);

  useEffect(() => {
    if (status) {
      let activeIndex = 0;
      switch (status) {
        case 'OrderReceived':
          activeIndex = 0;
          break;
        case 'Processing':
          activeIndex = 1;
          break;
        case 'ReadyToPickup':
          activeIndex = 2;
          break;
        case 'DeliveryOnWay':
          activeIndex = 3;
          break;
        case 'Delivered':
          activeIndex = 4;
          break;
      }
      setActiveStep(activeIndex);
    }
  }, [status]);

  function pollStatus(id) {
    setTimeout(async () => {
      const status = await fetchStatus(id);
      setStatus(status);
      if (status !== 'Delivered') {
        pollStatus(id);
      }
    }, 500);
  }

  async function fetchStatus(id) {
    return axios.get(`${baseUrl}/order/${id}`)
      .then(res => res.data)
      .then(data => data.status)
      .catch((e) => console.error(e));
  }

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" className={classes.title}>
            Demo: Event Driven Apps with Dapr in Kubernetes
          </Typography>
        </Toolbar>
      </AppBar>
      <Container maxWidth="sm">
        <Grid container style={{ marginTop: 40 }}>
          <Grid item xs={6} spacing={3}>
            <FormControl component="fieldset" className={classes.formControl}>
              <FormLabel component="legend">Food</FormLabel>
              <RadioGroup aria-label="food" name="food" value={food}
                onChange={(e) => setFood(e.target.value)}>
                <FormControlLabel value="pizza" control={<Radio />} label="Pizza ?" />
                <FormControlLabel value="burger" control={<Radio />} label="Burger ?" />
                <FormControlLabel value="sandwich" control={<Radio />} label="Sandwich ?" />
                <FormControlLabel value="hotdog" control={<Radio />} label="HotDog ?" />
                <FormControlLabel value="fries" control={<Radio />} label="Fries ?" />
              </RadioGroup>
            </FormControl>
          </Grid>
          <Grid item xs={6}>
            <FormControl component="fieldset" className={classes.formControl}>
              <FormLabel component="legend">Drink</FormLabel>
              <RadioGroup aria-label="drink" name="drink" value={drink}
                onChange={(e) => setDrink(e.target.value)}>
                <FormControlLabel value="drink1" control={<Radio />} label="Diet Coke" />
                <FormControlLabel value="drink2" control={<Radio />} label="Coke" />
                <FormControlLabel value="drink3" control={<Radio />} label="Coffee" />
                <FormControlLabel value="drink4" control={<Radio />} label="Iced Tea" />
                <FormControlLabel value="drink5" control={<Radio />} label="Beer" />
                <FormControlLabel value="drink6" control={<Radio />} label="Orange Juice" />
              </RadioGroup>
              <FormHelperText></FormHelperText>
            </FormControl>
          </Grid>
          <Button type="submit" variant="outlined" disabled={!(food && drink)}
            color="primary" className={classes.button}
            onClick={submitOrder}>
            {loading && <CircularProgress
              className={classes.spinner}
              size={20}
            />}
            Submit Order
          </Button>
        </Grid>
        {orderId && <Grid container style={{ marginTop: 50 }}>
          <Grid item>
            <Typography variant="h6" className={classes.title}>
              Order ID: {orderId}
            </Typography>
          </Grid>
          <Grid item>
            <Stepper activeStep={activeStep} alternativeLabel>
              {steps.map((label) => (
                <Step key={label}>
                  <StepLabel StepIconComponent={QontoStepIcon}>{label}</StepLabel>
                </Step>
              ))}
            </Stepper>
          </Grid>
        </Grid>
        }
      </Container>
    </div >
  );
}
Example #15
Source File: index.js    From yi-note with GNU General Public License v3.0 4 votes vote down vote up
Bookmarks = () => {
  const { t } = useTranslation('options');
  const { search } = useLocation();
  const {
    bookmarks: {
      bookmarks,
      tags,
      toolbar: { filtering, exporting, exportFormat }
    }
  } = useStoreState(state => state);
  const {
    fetchBookmarks,
    fetchTags,
    selectTag,
    toolbar: { setExportFormat }
  } = useStoreActions(actions => actions.bookmarks);

  useEffect(() => {
    let tagsFromUrl = [];
    const tagsStr = new URLSearchParams(search).get('tags');
    if (tagsStr) {
      tagsFromUrl = tagsStr.split(',');
    }
    fetchBookmarks();
    fetchTags(tagsFromUrl);
  }, [fetchBookmarks, fetchTags, search]);

  const handleSelectTag = tag => {
    selectTag(tag);
  };

  const handleExportFormatChange = e => setExportFormat(e.target.value);

  return (
    <StyledContainer>
      {bookmarks.length === 0 && !filtering ? (
        <NoBookmark />
      ) : (
        <Grid container>
          {exporting && (
            <Grid
              item
              container
              direction="row"
              alignItems="center"
              spacing={1}
            >
              <Grid item>
                <FormLabel>{t('bookmarks.export.format.label')}</FormLabel>
              </Grid>
              <Grid item>
                <RadioGroup
                  row
                  value={exportFormat}
                  onChange={handleExportFormatChange}
                >
                  <FormControlLabel
                    value="json"
                    control={<Radio size="small" />}
                    label="JSON"
                  />
                  <FormControlLabel
                    value="markdown"
                    control={<Radio size="small" />}
                    label="Markdown (no image)"
                  />
                </RadioGroup>
              </Grid>
            </Grid>
          )}
          {filtering && (
            <Grid item container spacing={1}>
              {tags.map(({ tag, selected }) => (
                <Grid item key={tag}>
                  <Chip
                    label={tag}
                    color={selected ? 'primary' : 'default'}
                    clickable
                    onClick={handleSelectTag.bind(null, tag)}
                  />
                </Grid>
              ))}
            </Grid>
          )}
          <Grid item>
            <List>
              {bookmarks.map(
                ({ id, title, description, url, image, selected }) => {
                  return (
                    <ListItem key={id}>
                      <BookmarkItem
                        id={id}
                        title={title}
                        description={description}
                        url={url}
                        image={image}
                        selected={selected}
                      />
                    </ListItem>
                  );
                }
              )}
            </List>
          </Grid>
        </Grid>
      )}
    </StyledContainer>
  );
}