@material-ui/pickers#KeyboardTimePicker JavaScript Examples

The following examples show how to use @material-ui/pickers#KeyboardTimePicker. 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: SchedulePost.js    From social-media-strategy-fe with MIT License 5 votes vote down vote up
SchedulePost = ({ postId, scheduledTime }) => {
	const [schedule, setSchedule] = useState(scheduledTime || new Date());
	const [invalidDate, setInvalidDate] = useState(false);
	const [modalOpen, setModalOpen] = useState(false);

	const dispatch = useDispatch();

	const handleChange = (date, e) => {
		console.log(e);
		setInvalidDate(false);
		setSchedule(date);
	};

	const handleSchedulePost = async () => {
		if (schedule > Date.now()) {
			await dispatch(scheduleTweet(postId, schedule));
		} else {
			setInvalidDate(true);
		}
	};

	return (
		<>
			<Button onClick={() => setModalOpen(true)} color="primary">
				{scheduledTime ? "Reschedule" : "Schedule"}
			</Button>
			<Modal
				open={modalOpen}
				handleClose={() => setModalOpen(false)}
				title="Schedule Post"
				handleConfirmation={handleSchedulePost}
			>
				<MuiPickersUtilsProvider utils={DateFnsUtils}>
					<Grid container direction="column" justify="space-around">
						<KeyboardDatePicker
							minDate={new Date()}
							margin="normal"
							id="date-picker-dialog"
							label="Date"
							format="MM/dd/yyyy"
							value={schedule}
							onChange={handleChange}
							KeyboardButtonProps={{
								"aria-label": "change date",
							}}
						/>
						<KeyboardTimePicker
							minDate={new Date()}
							margin="normal"
							id="time-picker"
							label="Time"
							value={schedule}
							onChange={handleChange}
							KeyboardButtonProps={{
								"aria-label": "change time",
							}}
						/>
						{invalidDate && (
							<Typography variant="caption" color="error">
								Invalid time
							</Typography>
						)}
					</Grid>
				</MuiPickersUtilsProvider>
			</Modal>
		</>
	);
}
Example #2
Source File: ReminderAction.js    From react-sample-projects with MIT License 5 votes vote down vote up
ReminderAction = ({ onAddReminder }) => {
  const [open, setOpen] = useState(false);
  const [selectedDate, setSelectedDate] = useState(new Date());

  const handleDateChange = (date) => {
    setSelectedDate(date);
  };
  const toggleReminder = () => {
    setOpen(() => !open);
  };

  const handleSave = () => {
    onAddReminder(selectedDate);
    toggleReminder();
  };

  return (
    <Box>
      <IconButton aria-label="Remind" onClick={toggleReminder}>
        <AlarmIcon />
      </IconButton>
      <Dialog
        open={open}
        onClose={toggleReminder}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">Remind</DialogTitle>
        <DialogContent>
          <DialogContentText>
            <MuiPickersUtilsProvider utils={DateFnsUtils}>
              <KeyboardDatePicker
                margin="normal"
                label="Date"
                format="MM/dd/yyyy"
                value={selectedDate}
                onChange={handleDateChange}
                KeyboardButtonProps={{
                  'aria-label': 'change date',
                }}
              />
              <KeyboardTimePicker
                margin="normal"
                label="Time"
                value={selectedDate}
                onChange={handleDateChange}
                KeyboardButtonProps={{
                  'aria-label': 'change time',
                }}
              />
            </MuiPickersUtilsProvider>
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={toggleReminder} color="primary">
            Cancel
          </Button>
          <Button onClick={handleSave} color="primary">
            Save
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
Example #3
Source File: DateTimeInput.jsx    From resilience-app with GNU General Public License v3.0 5 votes vote down vote up
DateTimeInput = ({ dateInputProps, onChange, required, timeInputProps, value }) => {
  const handleChange = (field, newValue) => {
    onChange({
      ...value,
      [field]: newValue,
    });
  };

  const datePickerContainerProps = {
    id: "datetime-input-date",
    label: "Date",
    margin: "normal",
    ...dateInputProps,
  };

  const timePickerProps = {
    id: "datetime-input-time",
    label: "Time",
    margin: "normal",
    ...timeInputProps,
  };

  return (
    <MuiPickersUtilsProvider utils={MomentUtils}>
      <KeyDatePickerContainer
        onChange={(val) => handleChange("date", val)}
        required={required}
        value={value.date}
        margin="normal"
        format="MM/dd/yyyy"
        KeyboardButtonProps={{
          "aria-label": "change date",
        }}
        {...datePickerContainerProps}
      />
      <KeyboardTimePicker
        value={value.time}
        required={required}
        onChange={(val) => handleChange("time", val)}
        KeyboardButtonProps={{ "aria-label": "change time" }}
        {...timePickerProps}
      />
    </MuiPickersUtilsProvider>
  );
}
Example #4
Source File: CreateQuiz.js    From Quizzie with MIT License 4 votes vote down vote up
function CreateQuiz() {
	const [quizName, setQuizName] = useState("");
	const [quizDate, setQuizDate] = useState(new Date());
	const [duration, setDuration] = useState(5);
	const [type, setType] = useState("private");

	const [loading, setLoading] = useState(false);
	const [redirect, setRedirect] = useState(false);
	const [redirectEdit, setRedirectEdit] = useState(false);
	const [quizId, setQuizId] = useState("");

	const [error, setError] = useState(false);

	const { executeRecaptcha } = useGoogleReCaptcha();

	const onQuizNameChange = (event) => {
		setQuizName(event.target.value);
	};

	const handleDateChange = (date) => {
		setQuizDate(date);
	};

	const handleTimeChange = (e, val) => {
		setDuration(val);
	};

	const onTypeChange = (event) => {
		setType(event.target.value);
	};

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

		let captcha = await executeRecaptcha("create_quiz");

		let data = {
			quizName: quizName,
			scheduledFor: quizDate.getTime(),
			quizDuration: duration,
			quizType: type,
			captcha: captcha,
		};

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

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

	if (loading) {
		return <Loading />;
	} else if (redirect) {
		return <Redirect to="/dashboard" />;
	} else if (redirectEdit) {
		return <Redirect to={`/editQuiz/${quizId}`} />;
	} else {
		return (
			<Container className="create-quiz-page">
				<div className="create-form">
					<Typography variant="h4" className="create-head">
						Quiz Details
					</Typography>
					<div className="create-form-inputs">
						<TextInput
							variant="outlined"
							label="Quiz Name"
							value={quizName}
							onChange={onQuizNameChange}
							name="Quiz Name"
							className="form-input"
						/>

						<MuiPickersUtilsProvider utils={DateFnsUtils}>
							<Grid
								className="date-time-select"
								container
								spacing={3}
							>
								<Grid item xs={12} sm={6}>
									<KeyboardDatePicker
										disableToolbar
										variant="inline"
										format="MM/dd/yyyy"
										margin="normal"
										label="Select Quiz Date"
										value={quizDate}
										onChange={handleDateChange}
									/>
								</Grid>
								<Grid item xs={12} sm={6}>
									<KeyboardTimePicker
										ampm={true}
										format="hh:mm:ss aa"
										views={["hours", "minutes", "seconds"]}
										margin="normal"
										label="Select Quiz Start Time"
										value={quizDate}
										onChange={handleDateChange}
										keyboardIcon={<AccessAlarm />}
									/>
								</Grid>
							</Grid>
						</MuiPickersUtilsProvider>
						<p style={{ marginTop: "5%", marginBottom: "5%" }}>
							Quiz Time (in minutes):
						</p>
						<Slider
							defaultValue={5}
							aria-labelledby="quiz time slider"
							step={5}
							min={5}
							max={60}
							valueLabelDisplay="on"
							marks
							className="time-slider"
							value={duration}
							onChange={handleTimeChange}
						/>
						<p>Select quiz type: </p>
						<Select
							value={type}
							onChange={onTypeChange}
							className="type-select"
						>
							<MenuItem value="public">Public</MenuItem>
							<MenuItem value="private">Private</MenuItem>
						</Select>

						<Button
							className="login-btn create-btn"
							onClick={handleSubmit}
						>
							Create Quiz
						</Button>
						<Typography
							variant="subtitle1"
							className="create-subtitle"
						>
							NOTE: After creating the quiz, you can add questions
							by editing the quiz in YOUR QUIZZES section of the
							dashboard.
						</Typography>
					</div>
				</div>
				<Snackbar
					open={error}
					autoHideDuration={5000}
					onClose={() => setError(false)}
				>
					<Alert
						variant="filled"
						severity="error"
						onClose={() => setError(false)}
					>
						There was a problem. Please try again!
					</Alert>
				</Snackbar>
			</Container>
		);
	}
}
Example #5
Source File: updateQuizDetails.js    From Quizzie with MIT License 4 votes vote down vote up
function UpdateQuizDetails(props) {
	const [quizId, setQuizId] = useState(props.match.params.id);
	const [quizName, setQuizName] = useState("");
	const [quizDate, setQuizDate] = useState(new Date());
	const [duration, setDuration] = useState(5);
	const [type, setType] = useState("private");

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

	const { executeRecaptcha } = useGoogleReCaptcha();

	const onQuizNameChange = (event) => {
		setQuizName(event.target.value);
	};

	const handleDateChange = (date) => {
		setQuizDate(date);
	};

	const handleTimeChange = (e, val) => {
		setDuration(val);
	};

	const onTypeChange = (event) => {
		setType(event.target.value);
	};

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

		let captcha = await executeRecaptcha("update_quiz_details");

		let updateOps = [
			{ propName: "quizName", value: quizName },
			{ propName: "scheduledFor", value: quizDate.getTime() },
			{ propName: "quizDuration", value: duration },
		];

		let data = {
			updateOps,
			captcha,
		};

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

	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) => {
					let details = res.data.result;
					setQuizName(details.quizName);
					setQuizDate(new Date(Number(details.scheduledFor)));
					setDuration(details.quizDuration);
					setType(details.quizType);
					setLoading(false);
				});
		} catch (error) {
			console.log(error);
			setLoading(false);
		}
	};

	useEffect(() => {
		getQuizDetails();
	}, []);

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

	if (loading) {
		return <Loading />;
	} else if (redirect) {
		return <Redirect to={`/editQuiz/${quizId}`} />;
	} else {
		return (
			<Container className="create-quiz-page">
				<div className="create-form">
					<Typography variant="h4" className="create-head">
						Quiz Details
					</Typography>
					<div className="create-form-inputs">
						<TextInput
							variant="outlined"
							label="Quiz Name"
							value={quizName}
							onChange={onQuizNameChange}
							name="Quiz Name"
							className="form-input"
						/>

						<MuiPickersUtilsProvider utils={DateFnsUtils}>
							<Grid
								className="date-time-select"
								container
								spacing={3}
							>
								<Grid item xs={12} sm={6}>
									<KeyboardDatePicker
										disableToolbar
										variant="inline"
										format="MM/dd/yyyy"
										margin="normal"
										label="Select Quiz Date"
										value={quizDate}
										onChange={handleDateChange}
									/>
								</Grid>
								<Grid item xs={12} sm={6}>
									<KeyboardTimePicker
										margin="normal"
										label="Select Quiz Start Time"
										value={quizDate}
										onChange={handleDateChange}
									/>
								</Grid>
							</Grid>
						</MuiPickersUtilsProvider>
						<p style={{ marginTop: "5%", marginBottom: "5%" }}>
							Quiz Time (in minutes):
						</p>
						<Slider
							defaultValue={5}
							aria-labelledby="quiz time slider"
							step={5}
							min={5}
							max={60}
							valueLabelDisplay="on"
							marks
							className="time-slider"
							value={duration}
							onChange={handleTimeChange}
						/>
						<p style={{ color: "#777" }}>Select quiz type: </p>
						<Tooltip title="Cannot change quiz type">
							<Select
								disabled
								value={type}
								onChange={onTypeChange}
								className="type-select"
							>
								<MenuItem value="public">Public</MenuItem>
								<MenuItem value="private">Private</MenuItem>
							</Select>
						</Tooltip>

						<Button
							className="login-btn create-btn"
							onClick={handleSubmit}
						>
							Update Quiz
						</Button>
					</div>
				</div>
			</Container>
		);
	}
}
Example #6
Source File: Scheduling.js    From TSS with MIT License 4 votes vote down vote up
render() {
    
    function Alert(props) {
      return <MuiAlert elevation={6} variant="filled" {...props} />;
    }

    const {sched} = data;
    const fin = localStorage.getItem("language");
    
    return (
      <div className="schedulingRoot">
        <Modal open={this.state.state!=='ready'?true:false} onClick={this.handleBackdropClick}>
          <Backdrop open={this.state.state!=='ready'?true:false} onClick={this.handleBackdropClick}>
            <CircularProgress disableShrink />
          </Backdrop>
        </Modal>

        {/* Section for selecting date */}
        <div className="firstSection">
          <form onSubmit={this.continueWithDate}>

            { /* Datepicker */}
            <MuiPickersUtilsProvider utils={MomentUtils} locale={lang} key={this.state.datePickerKey}>
              <KeyboardDatePicker
                autoOk
                margin="normal"
                name="date"
                label={sched.Day[fin]}
                value={this.state.date}
                onChange={date => this.handleDateChange(date)}
                onAccept={this.handleDatePickChange}
                format="DD.MM.YYYY"
                showTodayButton
              />
            </MuiPickersUtilsProvider>
            <div className="continue">
              <Button type="submit" variant="contained" style={{backgroundColor:'#d1ccc2'}}>{sched.Day[fin]}</Button>
            </div>
          </form>
        </div>

        <hr/>

        {/* Section for setting range officer status and open/close times of the tracks */}
        <div className="secondSection">
          <div className="topRow">
            <div className="text">{sched.Open[fin]}</div>

	    <Switch
              checked={ this.state.available }
              onChange={this.handleSwitchChange}
              name="available"
              color="primary"
              style={{color:'#5f77a1'}} />
          </div>
          <div className="middleRow">
            <div className="roSwitch">
              <div className="text">{sched.Supervisor[fin]}</div>
              <Switch
                className="officerSwitch"
                checked={this.state.rangeSupervisorSwitch}
                onChange={this.handleSwitchChange}
                name="rangeSupervisorSwitch"
                color="primary"
                style={{color:'#5f77a1'}} />
            </div>
            {this.createSupervisorSelect()}
          </div>
          <div className="bottomRow">
            <div className="text">{sched.OpenHours[fin]}</div>
            <MuiPickersUtilsProvider utils={MomentUtils} locale={'fi'}>
              <KeyboardTimePicker
                autoOk
                ampm={false}
                margin="normal"
                name="start"
                label={sched.Start[fin]}
                value={this.state.open}
                onChange={this.handleTimeStartChange}
                minutesStep={5}
                showTodayButton
              />
            </MuiPickersUtilsProvider>
            <div className="dash">-</div>
            <MuiPickersUtilsProvider utils={MomentUtils} locale={'fi'}>
              <KeyboardTimePicker
                autoOk
                ampm={false}
                margin="normal"
                name="end"
                label={sched.Stop[fin]}
                value={this.state.close}
                onChange={this.handleTimeEndChange}
                minutesStep={5}
                showTodayButton
              />
            </MuiPickersUtilsProvider>
          </div>
        </div>

        <hr/>

        {/* Section for setting track-specific open/close/absent statuses */}
        <div className="thirdSection">
          <div className="leftSide">
            {this.createTrackList()}
          </div>
          <div className="rightSide">
            <Button variant="contained" color="primary" onClick={this.openAllTracks} style={{color:'black', backgroundColor:'#5f77a1'}}>{sched.OpenAll[fin]}</Button>
            <Button variant="contained" onClick={this.emptyAllTracks} style={{backgroundColor:'#d1ccc2'}}>{sched.ClearAll[fin]}</Button>
        <Button variant="contained" color="secondary" onClick={this.closeAllTracks} style={{color:'black', backgroundColor:'#c97b7b'}}>{sched.CloseAll[fin]}</Button>
          </div>
        </div>
        <hr/>
        <div className="fourthSection">
          <div className="repetition">
            <div className="daily">
              {sched.RepeatDaily[fin]}
              <Switch
                checked={ this.state.daily }
                onChange={this.handleRepeatChange}
                id='daily'
                color="primary"
                style={{color:'#5f77a1'}}
              />
            </div>
            <div className="weekly">
              {sched.RepeatWeekly[fin]}
              <Switch
                checked={ this.state.weekly }
                onChange={this.handleRepeatChange}
                id='weekly'
                color="primary"
                style={{color:'#5f77a1'}}
              />
            </div>
            <div className="monthly">
              {sched.RepeatMonthly[fin]}
              <Switch
                checked={ this.state.monthly }
                onChange={this.handleRepeatChange}
                id='monthly'
                color="primary"
                style={{color:'#5f77a1'}}
              />
            </div>
            <div className="repeatCount">
              {sched.Amount[fin]}
              <TextField 
                name="repeatCount"
                type="number" 
                value={this.state.repeatCount} 
                onChange={this.handleValueChange}
                InputProps={{ inputProps: { min: 1, max: 100 } }}
              />
            </div>
          </div>
          <div className="save">
            <Button variant="contained" onClick={this.saveChanges} style={{backgroundColor:'#d1ccc2'}}>{sched.Save[fin]}</Button>
            <div
              className="hoverHand arrow-right"
              onClick={() => this.handleDatePickChange(moment(this.state.date).add(1, 'days').format('YYYY-MM-DD'))}
            ></div>
            <div className="toast">
              <Snackbar open={this.state.toast} autoHideDuration={5000} onClose={this.handleSnackbarClose}>
                <Alert onClose={this.handleSnackbarClose} severity={this.state.toastSeverity}>
                  {this.state.toastMessage}!
                </Alert>
              </Snackbar>
            </div>
          </div>
        </div>
      </div>
      
    );
  }
Example #7
Source File: rangeofficer.js    From TSS with MIT License 4 votes vote down vote up
TimePick = ({tablet, fin, scheduleId, hours, setHours, dialogOpen, setDialogOpen}) => {
  const [newHours, setNewHours] = useState({...hours});
  const [errorMessage, setErrorMessage] = useState();
  const [startDate, setStartDate] = useState(new Date(0,0,0, hours.start.split(":")[0], hours.start.split(":")[1], 0))
  const [endDate, setEndDate] = useState(new Date(0,0,0, hours.end.split(":")[0], hours.end.split(":")[1], 0))

  async function handleTimeChange(){
    if(startDate===null || endDate===null) {
      setErrorMessage(tablet.Error[fin])
      return
    }
    
    const start = startDate.toTimeString().split(" ")[0].slice(0, 5)
    const end = endDate.toTimeString().split(" ")[0].slice(0, 5)
    console.log(start, end)
    
    let query = "/api/schedule/" + scheduleId;
    let token = localStorage.getItem("token");
    const config = {
      headers: { Authorization: `Bearer ${token}` }
    };

    await axios.put(query,
                    {
                      open: start,
                      close: end
                    }, config)
      .then(res => {
        if(res) {
          setHours({"start": start, "end": end})
          setDialogOpen(false)
        }
      })
      .catch(error => {
        console.log(error)
        setErrorMessage(tablet.Error[fin])
      })
  }

  return (
    <div>
      <Dialog
        open={dialogOpen}
        aria-labelledby="title">
        <DialogTitle id="title" style={dialogStyle}>{tablet.PickTime[fin]}</DialogTitle>
        <DialogContent style={dialogStyle}>
          
          <div style={rowStyle}>
            <MuiPickersUtilsProvider utils={DateFnsUtils}>

              <KeyboardTimePicker
                margin="normal"
                id="starttime"
                label={tablet.Start[fin]}
                ampm={false}
                value={startDate}
                onChange={date => setStartDate(date)}
                minutesStep={5}
              />
              &nbsp;
              <KeyboardTimePicker
                margin="normal"
                id="endtime"
                label={tablet.End[fin]}
                ampm={false}
                value={endDate}
                onChange={date => setEndDate(date)}
                minutesStep={5}
              />

            </MuiPickersUtilsProvider>
          </div>
          
          <br />
          {errorMessage ?
           <Typography
             align="center"
             style={{color: "#c23a3a"}}>
             {errorMessage}
           </Typography>
           : ""}
          
        </DialogContent>

        <DialogActions style={dialogStyle}>
          <Button
            variant="contained"
            onClick={()=> setDialogOpen(false)}
            style={cancelButtonStyle}>
            {tablet.Cancel[fin]}
          </Button>
          
          <Button
            variant="contained"
            onClick={() => handleTimeChange()}
            style={saveButtonStyle}>
            {tablet.Save[fin]}
          </Button>
        </DialogActions>

      </Dialog>
    </div>
  )
}
Example #8
Source File: ModalContent.js    From Doto with MIT License 4 votes vote down vote up
ModalContent = props => {
    const classes = useStyles();

    const [selectedName, setSelectedName] = useState("TASK - " + new Date());
    const [selectedDescription, setSelectedDescription] = useState("");
    const [selectedDueDate, setSelectedDueDate] = useState(new Date());
    const [selectedEarliestDate, setEarliestDate] = useState(new Date());

    // default duration is 1 hour
    var initialDuration = new Date();
    initialDuration.setHours(1);
    initialDuration.setMinutes(0);
    const [selectedDuration, setSelectedDuration] = React.useState(initialDuration);

    // default travel time is 10 minutes unless specified
    const travelTime = new Date();
    travelTime.setHours(0);
    travelTime.setMinutes(10);
    const [selectedTravelTime, setSelectedTravelTime] = React.useState(travelTime);

    const [selectedLocation, setSelectedLocation] = useState("");
    const [selectedPriority, setSelectedPriority] = useState("");
    const [selectedReminder, setSelectedReminder] = useState("");
    const [dueDateValid, setDueDateValid] = useState(false);
    const [earliestDateValid, setEarliestDateValid] = useState(true);
    const [selectedCategory, setSelectedCategory] = useState("");

    // ----- HANDLERS FOR INPUT FIELDS -----
    const handleNameChange = event => {
        setSelectedName(event.target.value);
    };

    const handleDescriptionChange = event => {
        setSelectedDescription(event.target.value);
    };

    const handleDateChange = date => {
        if (date > new Date()) {
            setSelectedDueDate(date);
            setDueDateValid(true);
        } else {
            setSelectedDueDate("invalid date");
            setDueDateValid(false);
        }
    };

    const handleEarliestChange = date => {
        if (date >= new Date()) {
            setEarliestDate(date);
            setEarliestDateValid(true);
        } else {
            setEarliestDate("invalid date");
            setEarliestDateValid(false);
        }
    };

    const handleLocationChange = event => {
        setSelectedLocation(event.target.value);
    };

    const handlePriority = event => {
        setSelectedPriority(event.target.value);
    };

    const handleCategory = event => {
        setSelectedCategory(event.target.value);
    };

    const handleReminder = event => {
        setSelectedReminder(event.target.value);
    };

    // ----- END HANDLERS FOR INPUT FIELDS -----

    // Task variables passed into calendar.js to add new task to the calendar
    const handleAdd = event => {
        const task = {
            title: selectedName,
            description: selectedDescription,
            dueDate: selectedDueDate,
            earliestDate: selectedEarliestDate,
            duration: selectedDuration.getHours() * 60 + selectedDuration.getMinutes(),
            travelTime: selectedTravelTime.getHours() * 60 + selectedTravelTime.getMinutes(),
            location: selectedLocation,
            priority: selectedPriority,
            category: selectedCategory,
            reminder: selectedReminder,
        };

        props.addNewTask(task);
    };

    return (
        // Setting .css properties based on theme selected
        <div className={props.modalBackground === Themes.DARK ? "modal-p" : "modal-g"}>
            <div className="forum-content">
                <form className={classes.root} noValidate autoComplete="off">
                    <div>
                        <TextField
                            className="text-area name-field"
                            id="standard-basic"
                            label="Task name"
                            InputProps={{
                                classes: {
                                    input: classes.taskNameInput,
                                },
                            }}
                            InputLabelProps={{
                                classes: {
                                    root: classes.taskNameInput,
                                    shrink: classes.labelFocus,
                                },
                            }}
                            onChange={handleNameChange}
                        />
                    </div>
                    <div>
                        <TextField
                            className="text-area group-spacing"
                            id="standard-basic"
                            label="Task description"
                            onChange={handleDescriptionChange}
                        />
                    </div>
                    <div>
                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardDateTimePicker
                                disableToolbar
                                autoOk={true}
                                minDate={new Date()}
                                minDateMessage="Date must be after now"
                                invalidDateMessage="Date must be after now"
                                variant="inline"
                                format="MM/dd/yyyy HH:mm"
                                ampm={false}
                                margin="normal"
                                id="date-picker-inline"
                                label="Due Date"
                                value={selectedDueDate}
                                onChange={handleDateChange}
                                KeyboardButtonProps={{
                                    "aria-label": "Change date/time",
                                }}
                                error={!dueDateValid}
                            />
                        </MuiPickersUtilsProvider>
                    </div>
                    <div>
                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardDateTimePicker
                                disableToolbar
                                autoOk={true}
                                minDate={new Date()}
                                minDateMessage="Date must be after now"
                                invalidDateMessage="Date must be after now"
                                variant="inline"
                                format="MM/dd/yyyy HH:mm"
                                ampm={false}
                                margin="normal"
                                id="date-picker-inline"
                                label="Earliest Start"
                                value={selectedEarliestDate}
                                onChange={handleEarliestChange}
                                KeyboardButtonProps={{
                                    "aria-label": "Change date/time",
                                }}
                                error={!earliestDateValid}
                            />
                        </MuiPickersUtilsProvider>
                    </div>
                    <div>
                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardTimePicker
                                ampm={false}
                                label="Duration of task (hours : minutes)"
                                margin="normal"
                                id="time-picker"
                                value={selectedDuration}
                                onChange={setSelectedDuration}
                                KeyboardButtonProps={{
                                    "aria-label": "change time",
                                }}
                            />
                        </MuiPickersUtilsProvider>
                    </div>
                    <div>
                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardTimePicker
                                ampm={false}
                                label="Travel Duration (hours : minutes)"
                                margin="normal"
                                id="travel-time-picker"
                                value={selectedTravelTime}
                                onChange={setSelectedTravelTime}
                                KeyboardButtonProps={{
                                    "aria-label": "change time",
                                }}
                            />
                        </MuiPickersUtilsProvider>
                    </div>
                    <div>
                        <TextField
                            className="text-area spacing"
                            id="standard-basic"
                            label="Location"
                            onChange={handleLocationChange}
                        />
                    </div>
                    <div className="drop-down">
                        {/* Scheduling based on priority. Hight priority will schedule the task closer to current time. Low priority will
                        schedule task closer to deadline. */}
                        {/* TODO: Improve algorithm for more smarter Scheduling */}
                        <FormControl className={classes.formControl}>
                            <InputLabel id="priority-label">Priority</InputLabel>
                            <Select value={selectedPriority} onChange={handlePriority}>
                                <MenuItem value={10}>High</MenuItem>
                                <MenuItem value={20}>Medium</MenuItem>
                                <MenuItem value={30}>Low</MenuItem>
                            </Select>
                        </FormControl>
                    </div>
                    <div className="drop-down">
                        {/* Set task categories, the category will determine what colour the task has */}
                        <FormControl className={classes.formControl}>
                            <InputLabel id="category-label">Category</InputLabel>
                            <Select value={selectedCategory} onChange={handleCategory}>
                                <MenuItem value={1}>Homework</MenuItem>
                                <MenuItem value={2}>Work</MenuItem>
                                <MenuItem value={3}>Household</MenuItem>
                                <MenuItem value={4}>Personal</MenuItem>
                            </Select>
                        </FormControl>
                    </div>
                    <div className="drop-down">
                        {/* TODO: Send a reminder email to associated gmail address */}
                        <FormControl className={classes.formControl}>
                            <InputLabel id="reminder-label">Reminders</InputLabel>
                            <Select value={selectedReminder} onChange={handleReminder}>
                                <MenuItem value={10080}>1 Week Before</MenuItem>
                                <MenuItem value={1440}>1 Day Before</MenuItem>
                                <MenuItem value={60}>1 Hour Before</MenuItem>
                                <MenuItem value={30}>30 Minutes Before</MenuItem>
                                <MenuItem value={15}>15 Minutes Before</MenuItem>
                                <MenuItem value={5}>5 Minutes Before</MenuItem>
                            </Select>
                        </FormControl>
                        <Button
                            id="add-button"
                            variant="contained"
                            color="default"
                            onClick={handleAdd}
                            disabled={!(dueDateValid && earliestDateValid)}
                        >
                            ADD
                        </Button>
                    </div>
                </form>
            </div>
        </div>
    );
}
Example #9
Source File: SettingsPage.js    From Doto with MIT License 4 votes vote down vote up
WorkingHoursPicker = props => {
    const [dialog, setDialog] = useState(false);

    const handleClickOpen = () => {
        setDialog(true);
    };

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

    const handleCloseAndSave = () => {
        setDialog(false);
        props.saveChanges(props.startTime, props.endTime);
    };

    const handleStartTimeChange = date => {
        props.changeStartTime(date);
    };

    const handleEndTimeChange = date => {
        props.changeEndTime(date);
    };

    return (
        <Grid container>
            <h2 style={{ marginLeft: "10vw", marginTop: "4vh", textAlign: "left" }}>Working Hours:</h2>
            <div style={{ marginLeft: "3vw" }}>
                <MuiPickersUtilsProvider utils={DateFnsUtils}>
                    <KeyboardTimePicker
                        margin="normal"
                        label="Start Time"
                        value={props.startTime}
                        onChange={handleStartTimeChange}
                        KeyboardButtonProps={{
                            "aria-label": "change time",
                        }}
                    />
                </MuiPickersUtilsProvider>
            </div>
            <h2 style={{ marginLeft: "3vw", marginTop: "4vh", textAlign: "left" }}>to</h2>
            <div style={{ marginLeft: "3vw" }}>
                <MuiPickersUtilsProvider utils={DateFnsUtils}>
                    <KeyboardTimePicker
                        margin="normal"
                        label="End Time"
                        value={props.endTime}
                        onChange={handleEndTimeChange}
                        KeyboardButtonProps={{
                            "aria-label": "change time",
                        }}
                    />
                </MuiPickersUtilsProvider>
            </div>
            <div style={{ marginLeft: "3vw", marginTop: "3vh", textAlign: "left" }}>
                <Button variant="contained" color="secondary" onClick={handleClickOpen}>
                    Save
                </Button>
                <Dialog
                    open={dialog}
                    onClose={handleClose}
                    aria-labelledby="alert-dialog-title"
                    aria-describedby="alert-dialog-description"
                >
                    <DialogTitle id="alert-dialog-title">{"Want to save those changes?"}</DialogTitle>
                    <DialogContent>
                        <DialogContentText id="alert-dialog-description">
                            Your time-table will be re-managed automatically. Please check again.
                        </DialogContentText>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={handleClose} color="primary">
                            Cancel
                        </Button>
                        <Button onClick={handleCloseAndSave} color="primary" autoFocus>
                            Ok
                        </Button>
                    </DialogActions>
                </Dialog>
            </div>
        </Grid>
    );
}
Example #10
Source File: UpdateModalContent.js    From Doto with MIT License 4 votes vote down vote up
UpdateModalContent = props => {
    const classes = useStyles();

    const [selectedName, setSelectedName] = useState(props.taskToUpdate.title);
    const [selectedDescription, setSelectedDescription] = useState(props.taskToUpdate.description);
    const [selectedDueDate, setSelectedDueDate] = useState(props.taskToUpdate.dueDate);
    const [selectedEarliestDate, setSelectedEarliestDate] = useState(props.taskToUpdate.earliestDate);

    // default duration is 1 hour
    var initialDuration = new Date();
    initialDuration.setHours(1);
    initialDuration.setMinutes(0);
    const [selectedDuration, setSelectedDuration] = React.useState(initialDuration);

    // default travel time is 10 minutes unless specified
    const travelTime = new Date();
    travelTime.setHours(0);
    travelTime.setMinutes(10);
    const [selectedTravelTime, setSelectedTravelTime] = React.useState(travelTime);

    const [selectedLocation, setSelectedLocation] = useState(props.taskToUpdate.location);
    const [selectedPriority, setSelectedPriority] = useState("");
    const [selectedReminder, setSelectedReminder] = useState("");
    const [dueDateValid, setDueDateValid] = useState(props.taskToUpdate.dueDate > new Date());
    const [earliestDateValid, setEarliestDateValid] = useState(props.taskToUpdate.earliestDate >= new Date());
    const [selectedCategory, setSelectedCategory] = useState("");

    useEffect(() => {
        setSelectedName(props.taskToUpdate.title || "");
        setSelectedDescription(props.taskToUpdate.description || "");
        setSelectedDueDate(props.taskToUpdate.dueDate || "");
        setSelectedDuration(convertMinutesToDateTime(props.taskToUpdate.duration));
        setSelectedTravelTime(convertMinutesToDateTime(props.taskToUpdate.travelTime));
        setSelectedLocation(props.taskToUpdate.location || "");
        setSelectedCategory(props.taskToUpdate.category || "");
        setSelectedPriority(props.taskToUpdate.priority || "");
        setSelectedReminder(props.taskToUpdate.reminderType || "");
        setSelectedEarliestDate(props.taskToUpdate.earliestDate || "");
    }, [props.taskToUpdate]);

    // ----- HANDLERS FOR INPUT FIELDS -----
    const handleNameChange = event => {
        setSelectedName(event.target.value);
    };

    const handleDescriptionChange = event => {
        setSelectedDescription(event.target.value);
    };

    const handleDateChange = date => {
        if (date > new Date()) {
            setSelectedDueDate(date);
            setDueDateValid(true);
        } else {
            setSelectedDueDate("invalid date");
            setDueDateValid(false);
        }
    };

    const handleEarliestChange = date => {
        if (date >= new Date()) {
            setSelectedEarliestDate(date);
            setEarliestDateValid(true);
        } else {
            setSelectedEarliestDate("invalid date");
            setEarliestDateValid(false);
        }
    };

    const handleLocationChange = event => {
        setSelectedLocation(event.target.value);
    };

    const handlePriority = event => {
        setSelectedPriority(event.target.value);
    };

    const handleCategory = event => {
        setSelectedCategory(event.target.value);
    };

    const handleReminder = event => {
        setSelectedReminder(event.target.value);
    };

    const convertMinutesToDateTime = minutes => {
        const date = new Date();
        date.setMinutes(minutes % 60);
        date.setHours((minutes - (minutes % 60)) / 60);
        return date;
    };

    // ----- END HANDLERS FOR INPUT FIELDS -----

    // Task variables passed into calendar.js to add new task to the calendar
    const handleUpdate = event => {
        const task = {
            taskId: props.taskToUpdate.taskId,
            title: selectedName,
            description: selectedDescription,
            dueDate: selectedDueDate,
            earliestDate: selectedEarliestDate,
            duration: selectedDuration.getHours() * 60 + selectedDuration.getMinutes(),
            travelTime: selectedTravelTime.getHours() * 60 + selectedTravelTime.getMinutes(),
            location: selectedLocation,
            priority: selectedPriority,
            reminder: selectedReminder,
            category: selectedCategory,
        };

        props.onTaskUpdated(task);
    };

    return (
        // Setting .css properties based on theme selected
        <div className={props.modalBackground === Themes.DARK ? "modal-p" : "modal-g"}>
            <div className="forum-content">
                <form className={classes.root} noValidate autoComplete="off">
                    <div>
                        <TextField
                            className="text-area name-field"
                            id="standard-basic"
                            label="Task name"
                            InputProps={{
                                classes: {
                                    input: classes.taskNameInput,
                                },
                            }}
                            InputLabelProps={{
                                classes: {
                                    root: classes.taskNameInput,
                                    shrink: classes.labelFocus,
                                },
                            }}
                            onChange={handleNameChange}
                            defaultValue={selectedName}
                        />
                    </div>
                    <div>
                        <TextField
                            className="text-area group-spacing"
                            id="standard-basic"
                            label="Task description"
                            onChange={handleDescriptionChange}
                            defaultValue={selectedDescription}
                        />
                    </div>
                    <div>
                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardDateTimePicker
                                disableToolbar
                                autoOk={true}
                                minDate={new Date()}
                                minDateMessage="Date must be after now"
                                invalidDateMessage="Date must be after now"
                                variant="inline"
                                format="MM/dd/yyyy HH:mm"
                                ampm={false}
                                margin="normal"
                                id="date-picker-inline"
                                label="Due Date"
                                value={selectedDueDate}
                                onChange={handleDateChange}
                                KeyboardButtonProps={{
                                    "aria-label": "Change date/time",
                                }}
                                error={!dueDateValid}
                            />
                        </MuiPickersUtilsProvider>
                    </div>
                    <div>
                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardDateTimePicker
                                disableToolbar
                                autoOk={true}
                                minDate={new Date()}
                                minDateMessage="Date must be after now"
                                invalidDateMessage="Date must be after now"
                                variant="inline"
                                format="MM/dd/yyyy HH:mm"
                                ampm={false}
                                margin="normal"
                                id="date-picker-inline"
                                label="Earliest Start"
                                value={selectedEarliestDate}
                                onChange={handleEarliestChange}
                                KeyboardButtonProps={{
                                    "aria-label": "Change date/time",
                                }}
                                error={!earliestDateValid}
                            />
                        </MuiPickersUtilsProvider>
                    </div>
                    <div>
                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardTimePicker
                                ampm={false}
                                label="Duration of task (hours : minutes)"
                                margin="normal"
                                id="time-picker"
                                value={selectedDuration}
                                onChange={setSelectedDuration}
                                KeyboardButtonProps={{
                                    "aria-label": "change time",
                                }}
                            />
                        </MuiPickersUtilsProvider>
                    </div>
                    <div>
                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardTimePicker
                                ampm={false}
                                label="Travel Duration (hours : minutes)"
                                margin="normal"
                                id="travel-time-picker"
                                value={selectedTravelTime}
                                onChange={setSelectedTravelTime}
                                KeyboardButtonProps={{
                                    "aria-label": "change time",
                                }}
                            />
                        </MuiPickersUtilsProvider>
                    </div>
                    <div>
                        <TextField
                            className="text-area spacing"
                            id="standard-basic"
                            label="Location"
                            onChange={handleLocationChange}
                            defaultValue={selectedLocation}
                        />
                    </div>
                    <div className="drop-down">
                        {/* Scheduling based on priority. Hight priority will schedule the task closer to current time. Low priority will
                        schedule task closer to deadline. */}
                        {/* TODO: Improve algorithm for more smarter Scheduling */}
                        <FormControl className={classes.formControl}>
                            <InputLabel id="priority-label">Priority</InputLabel>
                            <Select value={selectedPriority} onChange={handlePriority}>
                                <MenuItem value={10}>High</MenuItem>
                                <MenuItem value={20}>Medium</MenuItem>
                                <MenuItem value={30}>Low</MenuItem>
                            </Select>
                        </FormControl>
                    </div>
                    <div className="drop-down">
                        {/* Set task categories, the category will determine what colour the task has */}
                        <FormControl className={classes.formControl}>
                            <InputLabel id="category-label">Category</InputLabel>
                            <Select value={selectedCategory} onChange={handleCategory}>
                                <MenuItem value={1}>Homework</MenuItem>
                                <MenuItem value={2}>Work</MenuItem>
                                <MenuItem value={3}>Household</MenuItem>
                                <MenuItem value={4}>Personal</MenuItem>
                            </Select>
                        </FormControl>
                    </div>
                    <div className="drop-down">
                        {/* TODO: Send a reminder email to associated gmail address */}
                        <FormControl className={classes.formControl}>
                            <InputLabel id="reminder-label">Reminders</InputLabel>
                            <Select value={selectedReminder} onChange={handleReminder}>
                                <MenuItem value={10080}>1 Week Before</MenuItem>
                                <MenuItem value={1440}>1 Day Before</MenuItem>
                                <MenuItem value={60}>1 Hour Before</MenuItem>
                                <MenuItem value={30}>30 Minutes Before</MenuItem>
                                <MenuItem value={15}>15 Minutes Before</MenuItem>
                                <MenuItem value={5}>5 Minutes Before</MenuItem>
                            </Select>
                        </FormControl>
                    </div>
                </form>
            </div>
            <div id="add-button">
                <Button
                    variant="contained"
                    color="default"
                    onClick={handleUpdate}
                    disabled={!(dueDateValid && earliestDateValid)}
                >
                    Update
                </Button>
            </div>
        </div>
    );
}