-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
692 lines (614 loc) · 22 KB
/
app.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
// Web app's Firebase configuration.
var firebaseConfig = {
apiKey: "AIzaSyB5kRc09ifanS9_tXPoOAPh2OYcYGZibM8",
authDomain: "my-things-to-do.firebaseapp.com",
databaseURL:
"https://my-things-to-do-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "my-things-to-do",
storageBucket: "my-things-to-do.appspot.com",
messagingSenderId: "701583012637",
appId: "1:701583012637:web:091b338bd38e88f345a7f4",
measurementId: "G-TE1EGL3L0M",
};
// Initialize Firebase.
firebase.initializeApp(firebaseConfig);
const database = firebase.database();
const auth = firebase.auth();
// Global variables.
// Main buttons variables.
const addTaskButton = document.querySelector("#add-button");
const sortTasksButton = document.querySelector("#sort-button");
const deleteAllTasksButton = document.querySelector("#delete-all-button");
const userProfileButton = document.querySelector("#user-button");
const logoutButton = document.querySelector("#logout-button");
const enterTask = document.querySelector("#task-title");
// Error modal variables.
const messageModal = document.querySelector("#message-modal");
const closeMessageModal = document.querySelector("#error-close");
const okButton = document.querySelector("#ok-button");
const message = document.querySelector("#error-message");
// User update profile modal variables.
const userModal = document.querySelector("#user-profile-modal");
const closeUserModal = document.querySelector("#user-close");
const updateEmailButton = document.querySelector("#update-email-button");
const updatePasswordButton = document.querySelector("#update-password-button");
const updateNameButton = document.querySelector("#update-name-button");
const deleteUserButton = document.querySelector("#delete-user-button");
const resetButton = document.querySelector("#update-reset-button");
const closeUpdateButton = document.querySelector("#update-close-button");
// Delete user modal variables.
const deleteUserModal = document.querySelector("#delete-user-modal");
const closeDeleteUserModal = document.querySelector("#delete-user-close");
const deleteUserCancelButton = document.querySelector(
"#delete-user-cancel-button"
);
const deleteUserConfirmButton = document.querySelector(
"#delete-user-confirm-button"
);
// Delete all tasks modal variables.
const deleteTasksModal = document.querySelector("#delete-tasks-modal");
const closeDeleteTasksModal = document.querySelector("#delete-close");
const deleteTasksCancelButton = document.querySelector("#delete-cancel-button");
const deleteTasksButton = document.querySelector("#delete-tasks-button");
let sort = false;
// Check if user is signed in.
auth.onAuthStateChanged(function (user) {
if (user) {
// User is signed in.
let email, displayName;
userId = user.uid;
email = user.email;
displayName = user.displayName;
document.querySelector("#welcome").innerText =
"Welcome " + displayName + "!";
writeUserData(displayName, email);
fetchAllData();
} else {
// Redirect to login-page.
email = null;
window.location.replace("login.html");
}
});
// Save user data in database.
const writeUserData = (displayName, email) => {
database.ref("users/" + userId).set({
displayName: displayName,
email: email,
});
getUserData();
};
// Get user data from database.
const getUserData = () => {
database.ref("users/" + userId).on("value", (snapshot) => {
let data = snapshot.val();
let email = data.email;
console.log("snapshot email: " + email);
let displayName = data.displayName;
console.log("snapshot displayName: " + displayName);
});
};
// Fetch all data with Firebase database.
const fetchAllData = () => {
database.ref(userId + "/todos/").once("value", function (snapshot) {
snapshot.forEach(function (ChildSnapshot) {
let task = ChildSnapshot.val();
let key = task.key;
addItemsToListView(task, key);
});
});
};
// Logout user from database.
const signOut = () => {
auth.signOut();
};
// EventListener for "enter" key used when adding new task.
const enterTaskEvent = (event) => {
if (event.keyCode === 13 || event.code === "Enter") {
event.preventDefault();
document.querySelector("#add-button").click();
}
};
// Read input when clicking on the "Add new task" button.
const createTask = () => {
const inputValue = document.querySelector("#task-title").value;
const dateValue = document.querySelector("#task-date").value;
const currentDate = new Date();
const givenDate = new Date(dateValue);
currentDate.setHours(0, 0, 0, 0);
if (inputValue === "" && dateValue === "") {
message.innerHTML = "Enter what you want to do and choose deadline date!";
showMessageModal();
} else if (inputValue === "") {
message.innerHTML = "Enter what you want to do!";
showMessageModal();
} else if (dateValue === "") {
message.innerHTML = "Choose deadline date!";
showMessageModal();
} else if (givenDate < currentDate) {
message.innerHTML = "The date must be bigger or equal to current date!";
showMessageModal();
} else {
addItemsToDatabase(inputValue, dateValue);
}
};
// Send task-items to Firebase database.
const addItemsToDatabase = (inputValue, dateValue) => {
let key = database
.ref()
.child(userId + "/todos/")
.push().key;
let description = "Task description";
let task = {
title: inputValue,
date: dateValue,
description: description,
timestamp: Date.now(),
done: false,
key: key,
};
let updates = {};
updates[userId + "/todos/" + key] = task;
database.ref().update(updates);
addItemsToListView(task, key);
};
// Add task-items to list-view.
const addItemsToListView = (task, key) => {
const listItem = document.createElement("li");
const taskTitle = document.createElement("p");
const taskDate = document.createElement("p");
const timestamp = document.createElement("p");
const taskInfo = document.createElement("p");
const taskButtons = document.createElement("div");
const taskData = document.createElement("div");
taskData.className = "task-data";
listItem.id = task.key;
taskTitle.innerHTML = task.title;
taskTitle.setAttribute("maxlength", "10");
taskTitle.setAttribute("contenteditable", false);
taskDate.innerHTML = task.date;
taskDate.className = "date";
taskDate.setAttribute("contenteditable", false);
timestamp.innerHTML = task.timestamp;
timestamp.className = "timestamp";
timestamp.style.display = "none";
taskInfo.innerHTML = task.description;
taskInfo.className = "description";
taskInfo.style.display = "none";
taskButtons.className = "task-buttons";
done = task.done;
taskData.appendChild(taskTitle);
taskData.appendChild(taskDate);
taskData.appendChild(taskInfo);
taskData.appendChild(timestamp);
// Add info-button at the end of task.
const buttonInfo = document.createElement("button");
const info = document.createElement("i");
info.setAttribute("class", "fas fa-info");
buttonInfo.setAttribute("id", "task-info-button");
buttonInfo.setAttribute(
"onclick",
"checkInfo(this.parentNode.parentNode, this.parentNode, this)"
);
buttonInfo.appendChild(info);
taskButtons.appendChild(buttonInfo);
// Add checkbox-button at the end of task.
const buttonCheckbox = document.createElement("button");
const checkbox = document.createElement("i");
checkbox.setAttribute("class", "fas fa-check");
buttonCheckbox.setAttribute("id", "task-done-button");
buttonCheckbox.setAttribute(
"onclick",
"taskChecked(this.parentNode.parentNode, this.parentNode, this)"
);
buttonCheckbox.appendChild(checkbox);
taskButtons.appendChild(buttonCheckbox);
// Add edit-button at the end of task.
const buttonEdit = document.createElement("button");
const editIcon = document.createElement("i");
editIcon.setAttribute("class", "fas fa-pencil-alt");
buttonEdit.setAttribute("id", "task-edit-button");
buttonEdit.setAttribute(
"onclick",
"taskEdit(this.parentNode.parentNode, this.parentNode, this)"
);
buttonEdit.appendChild(editIcon);
taskButtons.appendChild(buttonEdit);
// Add delete-button at the end of task.
const buttonDelete = document.createElement("button");
const deleteIcon = document.createElement("i");
deleteIcon.setAttribute("class", "fas fa-trash-alt");
buttonDelete.setAttribute("id", "task-delete-button");
buttonDelete.setAttribute(
"onclick",
"deleteTask(this.parentNode.parentNode)"
);
buttonDelete.appendChild(deleteIcon);
taskButtons.appendChild(buttonDelete);
listItem.appendChild(taskData);
listItem.appendChild(taskButtons);
// Check if task is done and set checked-class if it's true.
if (done === true) {
listItem.setAttribute("class", "checked");
buttonCheckbox.firstChild.setAttribute("class", "fas fa-check-double");
buttonCheckbox.setAttribute("class", "checked");
buttonEdit.setAttribute("class", "disabled");
buttonEdit.setAttribute("disabled", "true");
buttonInfo.setAttribute("class", "disabled");
buttonInfo.setAttribute("disabled", "true");
}
document.querySelector("#task-list").appendChild(listItem);
document.querySelector("#task-title").value = "";
document.querySelector("#task-date").value = "";
};
// Toggle sorting tasks due deadline-date and due created-date.
const sortTasks = () => {
let list, i, switching, listItem, dateValue, shouldSwitch, timestamp;
if (!sort) {
list = document.querySelector("#task-list");
switching = true;
while (switching) {
switching = false;
listItem = list.getElementsByTagName("LI");
for (i = 0; i < listItem.length - 1; i++) {
shouldSwitch = false;
dateValue = list.getElementsByClassName("date");
if (dateValue[i].innerHTML > dateValue[i + 1].innerHTML) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
listItem[i].parentNode.insertBefore(listItem[i + 1], listItem[i]);
switching = true;
}
}
sort = true;
} else if (sort) {
list = document.querySelector("#task-list");
switching = true;
while (switching) {
switching = false;
listItem = list.getElementsByTagName("LI");
for (i = 0; i < listItem.length - 1; i++) {
shouldSwitch = false;
timestamp = list.getElementsByClassName("timestamp");
if (timestamp[i].innerHTML > timestamp[i + 1].innerHTML) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
listItem[i].parentNode.insertBefore(listItem[i + 1], listItem[i]);
switching = true;
}
}
sort = false;
}
};
// Task description (end edit) when clicked on info-button.
const checkInfo = (listItem, taskButtons, buttonInfo) => {
buttonInfo.classList.toggle("checked");
taskInfo = listItem.childNodes[0].childNodes[2];
buttonCheck = taskButtons.childNodes[1];
buttonEdit = taskButtons.childNodes[2];
if (buttonInfo.className === "checked") {
buttonCheck.setAttribute("class", "disabled");
buttonCheck.setAttribute("disabled", "true");
buttonEdit.setAttribute("class", "disabled");
buttonEdit.setAttribute("disabled", "true");
taskInfo.style.display = "block";
taskInfo.setAttribute("contenteditable", true);
taskInfo.setAttribute("id", "info-editing");
taskInfo.addEventListener("keydown", (event) => {
if (event.keyCode === 13 || event.code === "Enter") {
event.preventDefault();
taskInfo.setAttribute("contenteditable", false);
updateTask(listItem);
}
});
} else if (listItem.className !== "checked") {
buttonCheck.removeAttribute("class", "disabled");
buttonCheck.removeAttribute("disabled");
buttonEdit.removeAttribute("class", "disabled");
buttonEdit.removeAttribute("disabled");
taskInfo.style.display = "none";
taskInfo.setAttribute("contenteditable", false);
taskInfo.setAttribute("id", "no-editing");
updateTask(listItem);
}
};
// Add "line-through" on task and set task to done when checkbox is checked.
const taskChecked = (listItem, taskButtons, buttonCheckbox) => {
listItem.classList.toggle("checked");
buttonInfo = taskButtons.childNodes[0];
buttonEdit = taskButtons.childNodes[2];
if (listItem.className === "checked") {
done = true;
buttonCheckbox.firstChild.setAttribute("class", "fas fa-check-double");
buttonCheckbox.setAttribute("class", "checked");
buttonInfo.setAttribute("class", "disabled");
buttonInfo.setAttribute("disabled", "true");
buttonEdit.setAttribute("class", "disabled");
buttonEdit.setAttribute("disabled", "true");
} else if (listItem.className !== "checked") {
done = false;
buttonCheckbox.firstChild.setAttribute("class", "fas fa-check");
buttonCheckbox.removeAttribute("class", "checked");
buttonInfo.removeAttribute("class", "disabled");
buttonInfo.removeAttribute("disabled");
buttonEdit.removeAttribute("class", "disabled");
buttonEdit.removeAttribute("disabled");
}
updateTask(listItem);
};
// Edit task when edit-button clicked.
const taskEdit = (listItem, taskButtons, buttonEdit) => {
buttonEdit.setAttribute("id", "task-edit-button-editing");
buttonEdit.setAttribute(
"onclick",
"finishEdit(this.parentNode.parentNode, this.parentNode, this)"
);
// taskTitle = listItem.childNodes[0];
taskTitle = listItem.childNodes[0].childNodes[0];
taskTitle.setAttribute("contenteditable", true);
taskTitle.setAttribute("id", "title-editing");
taskTitle.focus();
// taskDate = listItem.childNodes[1];
taskDate = listItem.childNodes[0].childNodes[1];
taskDate.setAttribute("contenteditable", true);
taskDate.setAttribute("id", "date-editing");
buttonInfo = taskButtons.childNodes[0];
buttonInfo.setAttribute("class", "disabled");
buttonInfo.setAttribute("disabled", "true");
buttonCheck = taskButtons.childNodes[1];
buttonCheck.setAttribute("class", "disabled");
buttonCheck.setAttribute("disabled", "true");
listItem.addEventListener("keydown", (event) => {
if (event.keyCode === 13 || event.code === "Enter") {
event.preventDefault();
finishEdit(listItem, taskButtons, buttonEdit);
}
});
};
// Finish editing task when edit-button clicked again (or enter when editing task).
const finishEdit = (listItem, taskButtons, buttonEdit) => {
const testTaskTitle = taskTitle.innerHTML;
const regex = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))$/;
const testDate = taskDate.innerHTML;
const match = regex.test(testDate);
if (match === false) {
message.innerHTML = "Enter date in format YYYY-MM-DD.";
showMessageModal();
} else if (testTaskTitle === "") {
message.innerHTML = "Enter task title!";
showMessageModal();
} else {
buttonEdit.setAttribute("id", "task-edit-button");
buttonEdit.setAttribute(
"onclick",
"taskEdit(this.parentNode.parentNode, this.parentNode, this)"
);
taskTitle = listItem.childNodes[0].childNodes[0];
taskTitle.setAttribute("contenteditable", false);
taskTitle.setAttribute("id", "no-editing");
taskDate = listItem.childNodes[0].childNodes[1];
taskDate.setAttribute("contenteditable", false);
taskDate.setAttribute("id", "no-editing");
buttonInfo = taskButtons.childNodes[0];
buttonInfo.removeAttribute("class", "disabled");
buttonInfo.removeAttribute("disabled", "true");
buttonCheck = taskButtons.childNodes[1];
buttonCheck.removeAttribute("class", "disabled");
buttonCheck.removeAttribute("disabled");
updateTask(listItem);
}
};
// Delete one task from the list when clicked on a "trash can" icon.
const deleteTask = (listItem) => {
listItem.style.display = "none";
let key = listItem.id;
database
.ref(userId + "/todos/")
.child(key)
.remove();
};
// Update task and send updated data to Firebase.
const updateTask = (listItem) => {
let key = listItem.id;
let updatedTask = {
title: listItem.childNodes[0].childNodes[0].innerHTML,
date: listItem.childNodes[0].childNodes[1].innerHTML,
description: listItem.childNodes[0].childNodes[2].innerHTML,
timestamp: listItem.childNodes[0].childNodes[3].innerHTML,
done: done,
key: key,
};
let updates = {};
updates[userId + "/todos/" + key] = updatedTask;
database.ref().update(updates);
};
// Edit and update user email.
const updateUserEmail = () => {
let user = firebase.auth().currentUser;
let newEmail = document.querySelector("#email").value;
if (newEmail !== "") {
user
.updateEmail(newEmail)
.then(function () {
// Update successful.
database.ref("users/" + userId).set({
displayName: user.displayName,
email: newEmail,
});
document.querySelector("#email").value = "";
hideModal(userModal);
message.innerHTML = "Email updated successfully";
showMessageModal();
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
message.innerHTML = errorMessage;
showMessageModal();
});
} else {
message.innerHTML = "Enter new email to update!";
showMessageModal();
}
};
// Edit and update user password.
const updateUserPassword = () => {
let user = firebase.auth().currentUser;
let newPassword = document.querySelector("#password").value;
if (newPassword !== "") {
user
.updatePassword(newPassword)
.then(function () {
// Update successful.
document.querySelector("#password").value = "";
hideModal(userModal);
message.innerHTML = "Password updated successfully";
showMessageModal();
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
message.innerHTML = errorMessage;
showMessageModal();
});
} else {
message.innerHTML = "Enter new password to update!";
showMessageModal();
}
};
// Edit and update user name.
const updateUserName = () => {
let user = firebase.auth().currentUser;
let newUsername = document.querySelector("#username").value;
if (newUsername !== "") {
user
.updateProfile({
displayName: newUsername,
})
.then(function () {
// Update successful.
database.ref("users/" + userId).set({
displayName: newUsername,
email: user.email,
});
document.querySelector("#welcome").innerText =
"Welcome " + newUsername + "!";
document.querySelector("#username").value = "";
hideModal(userModal);
message.innerHTML = "Name updated successfully";
showMessageModal();
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
message.innerHTML = errorMessage;
showMessageModal();
});
} else {
message.innerHTML = "Enter new name to update!";
showMessageModal();
}
};
// Reset input.
const resetInput = () => {
document.querySelector("#email").value = "";
document.querySelector("#password").value = "";
document.querySelector("#username").value = "";
};
// Show modal with delete-user-message.
const showDeleteUserModal = () => {
deleteUserCancelButton.setAttribute("onclick", "hideModal(deleteUserModal)");
deleteUserConfirmButton.setAttribute("onclick", "deleteUser()");
closeDeleteUserModal.setAttribute("onclick", "hideModal(deleteUserModal)");
deleteUserModal.style.display = "block";
window.onclick = function (event) {
if (event.target === deleteUserModal) {
hideModal(deleteUserModal);
}
};
};
// Delete user from database.
const deleteUser = () => {
var user = firebase.auth().currentUser;
user
.delete()
.then(function () {
// User deleted.
deleteAllTasks();
database.ref("users/" + userId).remove();
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
message.innerHTML = errorMessage;
showMessageModal();
});
};
// Show modal with error-message.
const showMessageModal = () => {
messageModal.style.display = "block";
okButton.setAttribute("onclick", "hideModal(messageModal)");
closeMessageModal.setAttribute("onclick", "hideModal(messageModal)");
window.onclick = function (event) {
if (event.target === messageModal) {
hideModal(messageModal);
}
};
};
// Show modal with delete-message.
const showDeleteModal = () => {
deleteTasksCancelButton.setAttribute(
"onclick",
"hideModal(deleteTasksModal)"
);
deleteTasksButton.setAttribute("onclick", "deleteAllTasks()");
closeDeleteTasksModal.setAttribute("onclick", "hideModal(deleteTasksModal)");
deleteTasksModal.style.display = "block";
window.onclick = function (event) {
if (event.target === deleteTasksModal) {
hideModal(deleteTasksModal);
}
};
};
// Delete all tasks from list and hide modal.
const deleteAllTasks = () => {
database.ref(userId + "/todos/").remove();
let list = document.querySelector("#task-list");
let listItem = list.getElementsByTagName("LI");
for (i = 0; i < listItem.length; i++) {
listItem[i].style.display = "none";
}
hideModal(deleteTasksModal);
};
// Show modal for user edit profile function.
const showUserModal = () => {
closeUpdateButton.setAttribute("onclick", "hideModal(userModal)");
closeUserModal.setAttribute("onclick", "hideModal(userModal)");
userModal.style.display = "block";
window.onclick = function (event) {
if (event.target === userModal) {
hideModal(userModal);
}
};
};
// Hide modal.
const hideModal = (modal) => {
modal.style.display = "none";
};
// Event listeners to buttons.
addTaskButton.addEventListener("click", createTask);
sortTasksButton.addEventListener("click", sortTasks);
deleteAllTasksButton.addEventListener("click", showDeleteModal);
userProfileButton.addEventListener("click", showUserModal);
logoutButton.addEventListener("click", signOut);
updateEmailButton.addEventListener("click", updateUserEmail);
updatePasswordButton.addEventListener("click", updateUserPassword);
updateNameButton.addEventListener("click", updateUserName);
resetButton.addEventListener("click", resetInput);
deleteUserButton.addEventListener("click", showDeleteUserModal);
enterTask.addEventListener("keydown", enterTaskEvent);