-
Notifications
You must be signed in to change notification settings - Fork 0
/
customcalendarcomponent.js
278 lines (221 loc) · 8.11 KB
/
customcalendarcomponent.js
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
function usePopup(start_value) {
const ID = "custom-popup";
let handleTransform = (popup, container) => {
let height = $(container).height();
popup.style.position = "absolute";
popup.style.transform = "translateY(" + (-height - 3) + "px)";
};
let handleClick = (ev) => {
ev.stopPropagation();
}
let getElement = () => {
return $("#" + ID);
};
let updateValue = () => {
if (getElement().length) {
getElement().html(this.value);
}
};
this.value = start_value;
this.popupExists = () => {
return $("#" + ID).length>0?true:false;
}
this.createPopup = (el) => {
let popup = $("<div></div>");
popup.html(this.value);
popup.addClass("popup");
popup.attr("id", ID);
$(el).append(popup);
handleTransform(popup[0], el);
$(popup).on("click", (ev)=> {
handleClick(ev);
});
};
this.destroyPopup = () => {
let popup = getElement();
$(popup).off("click", handleClick);
popup.remove();
};
this.setValue = (e) => {
this.value = e;
updateValue();
};
return [this.value, this.setValue, this.createPopup, this.destroyPopup, this.popupExists];
}
document.addEventListener('DOMContentLoaded', function() {
const currentDate = new Date();
const currentDateString = dateToYearMonthDay(currentDate);
let selectedDate = currentDate;
let getSelectedYear = ()=> selectedDate.getFullYear();
let getSelectedMonthNum = ()=> selectedDate.getMonth();
let getSelectedMonthAndYear = ()=> {
const month = selectedDate.toLocaleString('default', {month: 'long'});
const year = getSelectedYear();
return `${month}, ${year}`;
};
let getDaysInMonth = ()=> new Date(getSelectedYear(), getSelectedMonthNum() + 1, 0).getDate();
//Gets first and last day of month as index of the week. (Sunday:0, Monday:1, etc.)
let getFirstDayOfMonth = ()=> new Date(getSelectedYear(), getSelectedMonthNum()).getDay();
let getLastDayOfMonth = ()=> new Date(getSelectedYear(), getSelectedMonthNum()+1, 0).getDay();
var [currentPopupValue, setPopupValue, createPopup, destroyPopup, popupExists] = usePopup("");
//const popupManager = new PopupManager('Initial value');
let events = [];
init();
async function getEvents() {
try {
const response = await fetch("https://date.nager.at/api/v3/publicholidays/2024/US");
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const json = await response.json();
console.log(json);
for (let event of json) {
events.push({date: event.date, name: event.name});
}
} catch(ex) {
console.error(ex.message);
}
}
function dateToYearMonthDay(date) {
const dateObj = typeof(date)==Date ? date : new Date(date);
const month = dateObj.getUTCMonth() + 1; // months from 1-12
const day = dateObj.getUTCDate();
const year = dateObj.getUTCFullYear();
const newDate = month + "/" + day + "/" + year;
return newDate;
}
function getEvent(date) {
const results = events.filter((event)=>dateToYearMonthDay(date)==dateToYearMonthDay(event.date));
return results;
}
function populateDataCells() {
let body = $("#calendarBody");
body.empty();
let tableRow = $("<tr></tr>");
let cellIndex = 0;
let selected = null;
for (let i = 0; i < getFirstDayOfMonth(); i++) {
cellIndex++;
tableRow.append($(`<td class="empty"> </td>`));
}
for (let i = 1; i <= getDaysInMonth(); i++) {
let date = dateToYearMonthDay(new Date(getSelectedYear(), getSelectedMonthNum(), i));
let tableCellId = date.replaceAll("/","");
let eventsToday = getEvent(date);
cellIndex++;
let dayOfWeek = cellIndex % 7;
let classes = "";
if (date === currentDateString){
classes += "current-day ";
}
if (eventsToday.length > 0) classes += "has-events ";
let cell = $(
`<td class="${classes.trim()}" id=${tableCellId} tabindex=${eventsToday.length>0?0:-1}>
<span>${i}</span>
${
eventsToday.length > 0 ?
`<div class="event-data">
${eventsToday.map(()=> {
return (`
<div class="event"></div>
`);
}).join("")}
</div>` : ""
}
</td>`);
tableRow.append(cell);
if (eventsToday.length > 0) {
$(document.body).on("click", ()=> {
if (popupExists() && selected != null) {
deselectTableCell();
}
});
$(document).on("keydown", (ev)=> {
if (ev.key === "Tab") {
if (popupExists() && selected != null) {
deselectTableCell();
}
}
});
$(cell).on("click", (ev)=> {
if (!popupExists()) {
selectTableCell();
} else if (popupExists() && selected !== tableCellId) {
deselectTableCell();
selectTableCell();
}
ev.stopPropagation();
});
$(cell).on("keypress", function(ev) {
if (ev.key === "Enter") {
if (!popupExists()) {
selectTableCell();
} else if (popupExists() && selected !== tableCellId) {
deselectTableCell();
selectTableCell();
}
}
});
function deselectTableCell() {
$(`#${selected}`).removeClass("selected");
destroyPopup();
selected = null;
}
function selectTableCell() {
selected = tableCellId;
$(`#${selected}`).addClass("selected");
createPopup(cell);
setPopupValue(`${eventsToday.map((event) => event.name).join(", ")}<br/>${date}`);
}
}
if ((dayOfWeek == 0 && i != 0) || i == getDaysInMonth()) {
body.append(tableRow);
tableRow = $("<tr></tr>");
}
}
let lastChild = body.children().last();
for (let i = 0; i < 7-(getLastDayOfMonth()+1); i++) {
cellIndex++;
lastChild.append($(`<td class="empty"> </td>`));
}
}
function setMonthElement() {
let e = $("#monthText");
e.text(getSelectedMonthAndYear());
}
function reset() {
selectedDate = currentDate;
reloadCalendar();
}
function reloadCalendar() {
populateDataCells();
setMonthElement();
}
function setRelativeMonth(increment) {
selectedDate = new Date(getSelectedYear(), getSelectedMonthNum() + increment);
reloadCalendar();
}
function onLastMonthButtonClicked() {
setRelativeMonth(-1);
}
function onNextMonthButtonClicked() {
setRelativeMonth(1);
}
function onResetButtonClicked() {
reset();
}
async function init() {
setMonthElement();
await getEvents();
populateDataCells();
$("#lastMonthButton").on("click", () => {
onLastMonthButtonClicked();
})
$("#nextMonthButton").on("click", () => {
onNextMonthButtonClicked();
})
$("#resetButton").on("click", () => {
onResetButtonClicked();
})
}
});