-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathTimeIntervals.js
More file actions
91 lines (78 loc) · 2.45 KB
/
TimeIntervals.js
File metadata and controls
91 lines (78 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { HAS_DELAY_ON_START_TIME } from 'const';
import { formatTime } from 'utils';
const getTimeIntervals = (cutOffDate = 0) => {
const timeIntervals = [];
for (let i = 0; i < 24; i++) {
for (let j = 0; j < 4; j++) {
let time = new Date();
time.setHours(i);
time.setMinutes(j * 15);
time.setSeconds(0);
if (time.getTime() >= cutOffDate) {
timeIntervals.push(time);
}
}
}
return timeIntervals;
};
const isToday = (date) => {
return date?.setHours(0, 0, 0, 0) === new Date().setHours(0, 0, 0, 0);
};
const isTomorrow = (date) => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0, 0, 0, 0);
return date?.setHours(0, 0, 0, 0) === tomorrow.getTime();
};
// this function check if the user
// is in the last hour of the day
// to return the correct interval
// otherwise returns all intervals
const getIntervalForTomorrow = () => {
const now = new Date();
// In the last hour of the day
if (now > new Date().setHours(23, 0, 0, 0)) {
return new Date().setHours(0, now.getMinutes(), 0, 0);
}
return 0;
};
const getStartTimeInterval = (startDateIsToday) => {
return startDateIsToday ? Date.now() : 0;
};
const getStartTimeIntervalWithDelay = (date, startDateIsToday) => {
if (startDateIsToday) {
return new Date(Date.now() + 10 * 60 * 1000);
}
const startDateIsTomorrow = date ? isTomorrow(date) : false;
if (startDateIsTomorrow) {
return getIntervalForTomorrow();
}
return 0;
};
export default function TimeIntervals({ date, time, setTime, type } = {}) {
const startDateIsToday = date ? isToday(date) : false;
const startTimeInterval = HAS_DELAY_ON_START_TIME
? getStartTimeIntervalWithDelay(date, startDateIsToday)
: getStartTimeInterval(startDateIsToday);
const timeIntervals = getTimeIntervals(startTimeInterval);
// this enables setting start time inmediatly
if (startDateIsToday && !HAS_DELAY_ON_START_TIME) {
// push date now to the top of timeIntervals
timeIntervals[0] !== new Date() && timeIntervals.unshift(new Date());
}
return (
<>
{timeIntervals.map((itemValue, index) => (
<button
className={`button is-white dropdown-item has-text-grey${
itemValue === time ? ' is-active' : ''
}`}
onMouseDown={setTime(itemValue)}
key={`drop-down-${type}-${index}`}
>
{formatTime(itemValue)}
</button>
))}
</>
);
}