Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Time Picker Component for Recurring Events #240

Merged
merged 6 commits into from
Feb 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
298 changes: 231 additions & 67 deletions src/components/EventAdd/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@ import React, {
KeyboardEvent,
useCallback,
useContext,
useEffect,
useState,
useMemo,
} from 'react';
import { Immutable, castDraft } from 'immer';

import Button from '../Button';
import { classes, getRandomColor, timeToString } from '../../utils/misc';
import { classes, getRandomColor } from '../../utils/misc';
import { DAYS } from '../../constants';
import { ScheduleContext } from '../../contexts';
import { Event as EventData } from '../../types';
import Select from '../Select';

import './stylesheet.scss';

Expand All @@ -22,6 +23,12 @@ export type EventAddProps = {
setFormShown?: (next: boolean) => void;
};

export type Time = {
hour: number;
minute: number;
morning: boolean;
};

export default function EventAdd({
className,
event,
Expand All @@ -32,72 +39,108 @@ export default function EventAdd({
const [selectedTags, setSelectedTags] = useState(
event?.days ? [...event.days] : []
);
const [start, setStart] = useState(
event?.period.start ? timeToString(event.period.start, false, true) : ''
);
const [end, setEnd] = useState(
event?.period.end ? timeToString(event.period.end, false, true) : ''
);
const [submitDisabled, setSubmitDisabled] = useState(true);
const [error, setError] = useState('');
const [start, setStart] = useState<Time>({
hour: event?.period.start
? Math.floor(event.period.start / 60) % 12
? Math.floor(event.period.start / 60) % 12
: 12
: -1,
minute: event?.period.start ? event.period.start % 60 : -1,
morning: event?.period.start ? event.period.start < 720 : true,
});
const [end, setEnd] = useState<Time>({
hour: event?.period.end
? Math.floor(event.period.end / 60) % 12
? Math.floor(event.period.end / 60) % 12
: 12
: -1,
minute: event?.period.end ? event.period.end % 60 : -1,
morning: event?.period.end ? event.period.end < 720 : true,
});

const [renderCounter, setRenderCounter] = useState(0);

const parseTime = useCallback((time: Time): number => {
if (time.hour === -1 || time.minute === -1) {
return -1; // invalid time
}

let { hour } = time;
if (hour === 12) {
hour = 0;
}
if (!time.morning) {
hour += 12;
}
return hour * 60 + time.minute;
}, []);

const calculateError = (): string => {
const parsedStart = parseTime(start);
const parsedEnd = parseTime(end);

if (parsedEnd !== -1 && parsedEnd <= parsedStart) {
return 'Start time must be before end time.';
}
if (parsedStart !== -1 && (parsedStart < 480 || parsedEnd > 1320)) {
return 'Event must be between 08:00 AM and 10:00 PM.';
}
return '';
};

const error = calculateError();

useEffect(() => {
if (
const submitDisabled: boolean = useMemo(() => {
return !(
eventName.length > 0 &&
selectedTags.length > 0 &&
start !== '' &&
end !== '' &&
start.hour !== -1 &&
start.minute !== -1 &&
end.minute !== -1 &&
end.hour !== -1 &&
!error
) {
setSubmitDisabled(false);
} else {
setSubmitDisabled(true);
}
);
}, [eventName, selectedTags, start, end, error]);

const parseTime = useCallback((time: string): number => {
const split = time.split(':').map((str) => Number(str));

if (typeof split[0] !== 'undefined' && typeof split[1] !== 'undefined') {
return split[0] * 60 + split[1];
}
return -1; // invalid time string
}, []);
const timeChangeHelper = useCallback(
(newTime: Time, isStartTime: boolean): void => {
// validation
if (newTime.hour !== -1) {
if (newTime.hour !== -1 && newTime.hour < 1) {
newTime.hour = 1;
} else if (newTime.hour > 12) {
newTime.hour = 12;
}
}
if (newTime.minute !== -1) {
if (newTime.minute > 59) {
newTime.minute = 59;
}
}
// Updating state
if (isStartTime) {
setStart(newTime);
} else {
setEnd(newTime);
}
},
[]
);

const handleStartChange = useCallback(
(e: ChangeEvent<HTMLInputElement>): void => {
const newStart = e.target.value;

setError('');
setStart(newStart);

const parsedStart = parseTime(newStart);
const parsedEnd = parseTime(end);
if (parsedEnd !== -1 && parsedEnd <= parsedStart) {
setError('Start time must be before end time.');
} else if (parsedStart < 480 || parsedEnd > 1320) {
setError('Event must be between 08:00 AM and 10:00 PM.');
}
(newStart: Time): void => {
setRenderCounter(renderCounter + 1);
timeChangeHelper(newStart, true);
},
[end, parseTime]
[renderCounter, timeChangeHelper]
);

const handleEndChange = useCallback(
(e: ChangeEvent<HTMLInputElement>): void => {
const newEnd = e.target.value;

setError('');
setEnd(newEnd);

const parsedStart = parseTime(start);
const parsedEnd = parseTime(newEnd);
if (parsedStart !== -1 && parsedEnd <= parsedStart) {
setError('Start time must be before end time.');
} else if (parsedStart < 480 || parsedEnd > 1320) {
setError('Event must be between 08:00 AM and 10:00 PM.');
}
(newEnd: Time): void => {
setRenderCounter(renderCounter + 1);
timeChangeHelper(newEnd, false);
},
[start, parseTime]
[renderCounter, timeChangeHelper]
);

const onSubmit = useCallback((): void => {
Expand Down Expand Up @@ -145,8 +188,16 @@ export default function EventAdd({

setEventName('');
setSelectedTags([]);
setStart('');
setEnd('');
setStart({
minute: -1,
hour: -1,
morning: true,
});
setEnd({
minute: -1,
hour: -1,
morning: true,
});
}
}, [
event,
Expand Down Expand Up @@ -232,31 +283,43 @@ export default function EventAdd({
</tr>
<tr>
<td>
<div className={classes('label', start !== '' && 'active')}>
<div
className={classes(
'label',
parseTime(start) !== -1 && 'active'
)}
>
Start
</div>
</td>
<td className="input">
<input
type="time"
value={start}
<TimeInput
onChange={handleStartChange}
onKeyDown={handleKeyDown}
value={start}
key={`${start.hour}-${start.minute}-${
start.morning ? 'AM' : 'PM'
}-${renderCounter}`}
/>
</td>
</tr>
<tr>
<td>
<div className={classes('label', end !== '' && 'active')}>
<div
className={classes(
'label',
parseTime(end) !== -1 && 'active'
)}
>
End
</div>
</td>
<td className="input">
<input
type="time"
value={end}
<TimeInput
onChange={handleEndChange}
onKeyDown={handleKeyDown}
value={end}
key={`${end.hour}-${end.minute}-${
end.morning ? 'AM' : 'PM'
}-${renderCounter}`}
/>
</td>
</tr>
Expand All @@ -278,3 +341,104 @@ export default function EventAdd({
</div>
);
}

export type TimeInputProps = {
value: Time;
onChange: (newTime: Time) => void;
};

function TimeInput(props: TimeInputProps): React.ReactElement {
const { value } = props;

const initHour =
value.hour === -1 ? '' : value.hour.toString().padStart(2, '0');
const initMinute =
value.minute === -1 ? '' : value.minute.toString().padStart(2, '0');
const initMorning = value.morning;

const [hour, setHour] = useState(initHour);
const [minute, setMinute] = useState(initMinute);
const [morning] = useState(initMorning);

const { onChange } = props;

const getTime = useCallback(
(actualMorning?: boolean): Time => {
const hourNum = hour ? parseInt(hour, 10) : -1;
const minuteNum = minute ? parseInt(minute, 10) : -1;
const usedMorning = actualMorning === undefined ? morning : actualMorning;
return {
hour: hourNum,
minute: minuteNum,
morning: usedMorning,
};
},
[hour, minute, morning]
);

function handleHourChange(e: ChangeEvent<HTMLInputElement>): void {
const re = /^[0-9\b]+$/;

// if value is not blank, then test the regex
if (e.target.value === '' || re.test(e.target.value)) {
setHour(e.target.value);
}
}

function formatHour(): void {
onChange(getTime());
}

function handleMinuteChange(e: ChangeEvent<HTMLInputElement>): void {
const re = /^[0-9\b]+$/;

// if value is not blank, then test the regex
if (e.target.value === '' || re.test(e.target.value)) {
setMinute(e.target.value);
}
}

function formatMinute(): void {
onChange(getTime());
}

const handleMorningChange = useCallback(
(newId: string): void => {
onChange(getTime(newId === 'am'));
},
[getTime, onChange]
);

return (
<>
<input
className="time"
type="text"
maxLength={2}
placeholder="--"
value={hour}
onChange={handleHourChange}
onBlur={formatHour}
/>
<div className="colon">:</div>
<input
className="time"
type="text"
maxLength={2}
placeholder="--"
value={minute}
onChange={handleMinuteChange}
onBlur={formatMinute}
/>
<Select
onChange={handleMorningChange}
current={morning ? 'am' : 'pm'}
options={[
{ id: 'am', label: 'AM' },
{ id: 'pm', label: 'PM' },
]}
className="ampm"
/>
</>
);
}
Loading
Loading