-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
483 lines (414 loc) · 18.6 KB
/
script.js
File metadata and controls
483 lines (414 loc) · 18.6 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
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
// DONE: FIX ID SYSTEM, BROKEN WHEN DELETING TASKS
// TO IMPLEMENT: DELETE ALL COMPLETED TASKS FUNCTION
// TO IMPLEMENT: DELETE ALL TASKS FUNCTION
// MORE FEATURES TO IMPLEMENT...
// TO IMPLEMENT: DRAGGABLE DIVS
// TO IMPLEMENT: Animations..
// TO IMPLEMENT: EDIT FUNCTION ON THE SIDE
/**
* HelperFunction class containing utility methods.
*/
class HelperFunctions {
/**
*
* @param {string} filename
* @returns {string} The SVG data representing the SVG
*/
static async fetchSvgIcon(filename) {
try {
const response = await fetch(`assets/svgs/${filename}`);
const svgData = await response.text();
return svgData;
} catch (error) {
console.error(error);
return null;
}
}
}
/**
* Task Class which handles adding/deleting/displaying/editing the task list
*/
class Task {
/**
* Constructor for the Task Class
* Initializes task dictionaries and the number of task(uncompleted, completed, total)
* Initializes the display of current tasks/completed tasks
*/
constructor() {
this.taskList = document.getElementById("task-list");
this.taskDictionary = localStorage.getItem('task-items') ? JSON.parse(localStorage.getItem('task-items')) : {};
this.taskDictionaryKeysArray = Object.keys(this.taskDictionary);
this.completedTaskList = document.getElementById("completed-task-list");
this.completedTaskDictionary = localStorage.getItem('completed-task-items') ? JSON.parse(localStorage.getItem('completed-task-items')) : {};
this.completedTaskDictionaryKeysArray = Object.keys(this.completedTaskDictionary);
this.currentNumberOfTasks = this.taskDictionaryKeysArray.length;
this.numberOfCompletedTask = this.completedTaskDictionaryKeysArray.length;
this.historicNumberOfTasks = parseInt(localStorage.getItem('historic-number-of-tasks') ? localStorage.getItem('historic-number-of-tasks') : 0); // For ID purposes
console.log(this.completedTaskDictionary)
this.initializeTaskList();
this.initializeCompletedTaskList();
}
/**
* Initializes the display of current task(s)
*/
initializeTaskList() {
for (let i = 0; i < this.currentNumberOfTasks; i++) {
let taskId = this.taskDictionaryKeysArray[i]
let taskContent = this.taskDictionary[taskId]
this.displayTask(taskId, taskContent)
}
}
/**
* Initializes the display of completed task(s)
*/
initializeCompletedTaskList() {
for (let i = 0; i < this.numberOfCompletedTask; i++) {
let taskId = this.completedTaskDictionaryKeysArray[i]
let taskContent = this.completedTaskDictionary[taskId]
this.displayCompletedTask(taskId, taskContent)
this.displayNumberCompletedNumberOfTasks();
}
}
/**
*
* @returns {int} The number of Current Task
*/
getCurrentNumberOftasks() {
return this.currentNumberOfTasks;
}
/**
* Increments and update the current number Of Task and total task(ID purposes)
*/
incrementNumberOfTasks() {
this.currentNumberOfTasks += 1;
this.historicNumberOfTasks += 1;
localStorage.setItem('historic-number-of-tasks', String(this.historicNumberOfTasks))
console.log(this.historicNumberOfTasks) ; // check first if the historic number is being stored between sessions
}
decrementNumberOfTasks() {
this.currentNumberOfTasks -= 1;
}
/**
* Increments/Decrements the number of Completed Task and also update the display of the number of completed task at the bottom of the frame
*/
incrementNumberOfCompletedTasks() {
this.numberOfCompletedTask += 1;
this.displayNumberCompletedNumberOfTasks();
}
decrementNumberOfCompletedTasks() {
this.numberOfCompletedTask -= 1;
this.displayNumberCompletedNumberOfTasks();
}
/**
* Do not increment the number of Completed Task but display the completed number of task at the bottom of the frame
*/
displayNumberCompletedNumberOfTasks() {
var completedTaskNumber = document.getElementById("completed-task-number");
completedTaskNumber.textContent = this.numberOfCompletedTask;
}
/**
* Main component on adding task to the dictionary and then displaying it as well as incrementing the number of task
* @param {string} content The description of the task
*/
addTask(content) {
let keyId = `task-${this.historicNumberOfTasks+1}`
this.addItemToDictionary(keyId, content);
this.displayTask(keyId, content)
this.incrementNumberOfTasks();
}
/**
* Sub-component/helper function for addTask, this function adds the the parameter content to the dictionary giving it an ID specified in the parameter KeyId
* @param {string} keyId Unique ID to be used for the dictionary
* @param {string} content The description of the task
*/
addItemToDictionary(keyId, content) {
this.taskDictionary[keyId] = content
localStorage.setItem('task-items', JSON.stringify(this.taskDictionary));
}
/**
* Main component of creating and appending the elements to be displayed in the task-list div in the website, appends the task-list-item div to the task-list div
* @param {string} taskId Unique ID to be used for the dictionary
* @param {string} content The description of the task
*/
displayTask(taskId, content) {
// Initialize IDs
let currentTaskId = taskId;
let checkboxId = `checkbox-${currentTaskId}`;
let editButtonId = `edit-button-${currentTaskId}`;
let deleteButtonId = `delete-button-${currentTaskId}`
// configure task-list-item div
const task = document.createElement("div");
task.id = currentTaskId;
task.classList.add("frame__task-list-item");
task.draggable = true;
// configure checkbox input box
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = checkboxId;
checkbox.classList.add("checkmark-checkbox");
// configure checkmark label tag
const checkmarkLabel = document.createElement("label");
checkmarkLabel.htmlFor = checkboxId;
checkmarkLabel.classList.add("checkmark-label");
// import checkmark image
const checkMarkImage = document.createElement("i");
checkMarkImage.classList.add("fas", "fa-check");
// create and configure hidable/focusable div to contain buttons
const focusableIconDiv = document.createElement("div");
focusableIconDiv.classList.add("focus-show-button");
// configure edit button inside focusableIconDiv
// const editButton = document.createElement("button");
// editButton.type = "button";
// editButton.id = editButtonId
// editButton.classList.add("edit-task-button");
// fetch('assets/svgs/editicon.svg').then(response => response.text()).then(data => {editButton.innerHTML = data;}).catch(error => console.error(error));
// configure delete button inside focusableIconDiv
const deleteButton = document.createElement("button");
deleteButton.type = "button";
deleteButton.id = deleteButtonId;
deleteButton.classList.add("delete-task-button");
fetch('assets/svgs/trashicon.svg').then(response => response.text()).then(data => {deleteButton.innerHTML = data;}).catch(error => console.error(error));
deleteButton.addEventListener('click', handleDeleteButtons);
// set the task description from the input box
const taskDescription = document.createElement("span");
taskDescription.textContent = content;
// join/nest the elements together
task.appendChild(checkbox);
task.appendChild(checkmarkLabel).appendChild(checkMarkImage);
// focusableIconDiv.appendChild(editButton);
focusableIconDiv.appendChild(deleteButton);
task.appendChild(focusableIconDiv);
task.appendChild(taskDescription);
// Finally, append the newly created task-item to the task-list
this.taskList.appendChild(task);
}
/**
* Main component of creating and appending the elements to be displayed in the task-list div in the website, appends the task-list-item div to the task-list div
* NOTE: Only used for initialization
* @param {string} taskId Unique ID to be used for the dictionary
* @param {string} content The description of the task
*/
displayCompletedTask(taskId, content) {
// Initialize IDs
let currentTaskId = taskId;
let checkboxId = `checkbox-${currentTaskId}`;
let editButtonId = `edit-button-${currentTaskId}`;
let deleteButtonId = `delete-button-${currentTaskId}`
// configure task-list-item div
const task = document.createElement("div");
task.id = currentTaskId;
task.classList.add("frame__task-list-item", "complete");
task.draggable = true;
// configure checkbox input box
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = true;
checkbox.id = checkboxId;
checkbox.classList.add("checkmark-checkbox");
// configure checkmark label tag
const checkmarkLabel = document.createElement("label");
checkmarkLabel.htmlFor = checkboxId;
checkmarkLabel.classList.add("checkmark-label");
// import checkmark image
const checkMarkImage = document.createElement("i");
checkMarkImage.classList.add("fas", "fa-check");
// create and configure hidable/focusable div to contain buttons
const focusableIconDiv = document.createElement("div");
focusableIconDiv.classList.add("focus-show-button");
// configure edit button inside focusableIconDiv
const editButton = document.createElement("button");
editButton.type = "button";
editButton.id = editButtonId
editButton.classList.add("edit-task-button");
fetch('assets/svgs/editicon.svg').then(response => response.text()).then(data => {editButton.innerHTML = data;}).catch(error => console.error(error));
// configure delete button inside focusableIconDiv
const deleteButton = document.createElement("button");
deleteButton.type = "button";
deleteButton.id = deleteButtonId;
deleteButton.classList.add("delete-task-button");
fetch('assets/svgs/trashicon.svg').then(response => response.text()).then(data => {deleteButton.innerHTML = data;}).catch(error => console.error(error));
deleteButton.addEventListener('click', handleDeleteButtons);
// set the task description from the input box
const taskDescription = document.createElement("span");
taskDescription.textContent = content;
// join/nest the elements together
task.appendChild(checkbox);
task.appendChild(checkmarkLabel).appendChild(checkMarkImage);
focusableIconDiv.appendChild(editButton);
focusableIconDiv.appendChild(deleteButton);
task.appendChild(focusableIconDiv);
task.appendChild(taskDescription);
// Finally, append the newly created task-item to the task-list
this.completedTaskList.appendChild(task);
}
//TEMPORARY
deleteAllTask() {
// Gets the parent node (div that contains the checkbox) then remove it from the page and update localStorage
this.taskDictionary = {};
localStorage.setItem("task-items", JSON.stringify(this.taskDictionary))
localStorage.setItem("completed-task-items", JSON.stringify(this.taskDictionary))
localStorage.setItem("historic-number-of-tasks", "0"); // localStorage can only accept String, but will be convert to int later with parseInt
}
deleteTask(targetElementId) {
const parentDivNode = document.getElementById(targetElementId).parentNode.parentNode // delete-button -> focusable-div -> task-list-item so parentNode.parentNode
const parentDivNodeId = parentDivNode.id;
// Delete from the dictionary and localStorage
delete this.taskDictionary[parentDivNodeId]
parentDivNode.remove()
localStorage.setItem("task-items", JSON.stringify(this.taskDictionary))
}
/**
* Deletes the completed task
* @param {string} targetElementId the ID of the completed task element that is to be deleted
*/
deleteCompletedTask(targetElementId) {
const parentDivNode = document.getElementById(targetElementId).parentNode.parentNode // delete-button -> focusable-div -> task-list-item so parentNode.parentNode
const parentDivNodeId = parentDivNode.id;
// Delete from the dictionary and localStorage
delete this.completedTaskDictionary[parentDivNodeId]
parentDivNode.remove()
localStorage.setItem("completed-task-items", JSON.stringify(this.completedTaskDictionary))
this.decrementNumberOfCompletedTasks();
}
/**
* Completes the task after the user has "checked" the checkbox
* Gets the parent node of the "checked" checkbox then clone it
* Assigns a new Id for the checkbox/checkbox label to differentiate it with uncompleted task
* Deletes the parent node, removing it from being displayed
* Adds the text content of the - to be deleted element - to the completedTaskDictionary with the newly generated Id
* Removes the parentNode, and append the cloned parentNode to the completed-task-list div, this displays the completed task from task-list div to the completed-task-list div
* Sets the localStorage to store the changes, then update the completed number of tasks and its display
* @param {string} targetElementId the ID of the checkbox to be completed
*/
completeTask(targetElementId) {
const parentNode = document.getElementById(targetElementId).parentElement;
const parentNodeClone = parentNode.cloneNode(true);
parentNodeClone.classList.add("complete")
const checkboxId = targetElementId;
const parentNodeId = parentNode.id
// checkbox/label respectively
// also attaches eventlisteners
parentNodeClone.childNodes[0].id = checkboxId
parentNodeClone.childNodes[1].htmlFor = checkboxId
parentNodeClone.querySelector(`#delete-button-${parentNodeId}`).addEventListener("click", handleDeleteButtons)
delete this.taskDictionary[parentNodeId];
parentNode.remove();
this.completedTaskDictionary[parentNodeId] = parentNode.lastChild.textContent; // LastChild should be the span containing the content
document.getElementById("completed-task-list").appendChild(parentNodeClone);
// Update localStorage
localStorage.setItem("completed-task-items", JSON.stringify(this.completedTaskDictionary));
localStorage.setItem("task-items", JSON.stringify(this.taskDictionary));
// No need to call display since it is already displayed by appendChild above
this.incrementNumberOfCompletedTasks();
}
/**
* Uncompletes the task after the user has "unchecked" the checkbox
* Gets the parent node of the "unchecked" checkbox then clone it
* Assigns a new Id for the checkbox/checkbox label to differentiate it with uncompleted task
* Deletes the parent node, removing it from being displayed
* Adds the text content of the - to be deleted element - to the taskDictionary with the reverted Id
* Removes the parentNode, and append the cloned parentNode to the task-list div, this displays the uncompleted task from completed-task-list div to the task-list div
* Sets the localStorage to store the changes, then decrement the completed number of tasks and its display
* @param {string} targetElementId the ID of the task element to be completed
*/
unCompleteTask(targetElementId) {
const parentNode = document.getElementById(targetElementId).parentElement;
const parentNodeClone = parentNode.cloneNode(true);
parentNodeClone.classList.remove("complete")
const checkboxId = targetElementId;
const parentNodeId = parentNode.id;
// checkbox/label respectively
// also attaches eventlisteners
parentNodeClone.childNodes[0].id = checkboxId
parentNodeClone.childNodes[1].htmlFor = checkboxId
parentNodeClone.querySelector(`#delete-button-${parentNodeId}`).addEventListener("click", handleDeleteButtons)
delete this.completedTaskDictionary[parentNodeId];
parentNode.remove();
this.taskDictionary[parentNodeId] = parentNode.lastChild.textContent; // Slices "completed-" from the Id
document.getElementById("task-list").appendChild(parentNodeClone);
// Update localStorage
localStorage.setItem("completed-task-items", JSON.stringify(this.completedTaskDictionary));
localStorage.setItem("task-items", JSON.stringify(this.taskDictionary));
// Decrease completed count and update the display
this.numberOfCompletedTask -= 1
this.displayNumberCompletedNumberOfTasks();
}
}
// helper functions
// Initializing the Task class
const taskInstance = new Task();
// EVENT LISTENERS
// add task button event listener
const addTaskButton = document.getElementById("add-task-btn");
var inputField = document.getElementById("task-text-input");
addTaskButton.addEventListener("click", function() {
taskInstance.addTask(inputField.value);
inputField.value = "";
});
// Input Field "Enter" listener
var inputField = document.getElementById("task-text-input");
inputField.addEventListener("keydown", function(event) {
if (event.key == "Enter") {
taskInstance.addTask(inputField.value);
inputField.value = "";
}
});
// add task button event listener
const completedTaskButtons = document.querySelectorAll(".completed-task-button");
completedTaskButtons.forEach((completedTaskButton) => {
completedTaskButton.addEventListener("click", function() {
let taskList = document.getElementById("task-list");
let completedTaskList = document.getElementById("completed-task-list");
if (taskList.classList.contains("hidden")) {
taskList.classList.remove("hidden");
completedTaskList.classList.add("hidden");
document.querySelector(".frame__task-list-header").innerHTML = "Task List";
document.getElementById("completed-task-button").classList.remove("hidden");
document.getElementById("hide-completed-task-button").classList.add("hidden");
}
else {
taskList.classList.add("hidden");
completedTaskList.classList.remove("hidden");
document.querySelector(".frame__task-list-header").innerHTML = "Completed Tasks";
document.getElementById("completed-task-button").classList.add("hidden");
document.getElementById("hide-completed-task-button").classList.remove("hidden");
}
});
});
// Event handler function
function handleCheckboxChange(event) {
if (event.target && event.target.classList.contains("checkmark-checkbox")) {
const targetElementId = event.target.id;
if (event.target.parentNode.classList.contains("complete")) {
taskInstance.unCompleteTask(targetElementId);
} else {
taskInstance.completeTask(targetElementId);
}
}
}
function handleDeleteButtons(event) {
const targetButtonId = event.target.id
const taskListItemDivNode = event.target.parentNode.parentNode // Button -> focusableDiv -> tasklist-item hence parentNode.parentNode
if (taskListItemDivNode.classList.contains("complete")) {
taskInstance.deleteCompletedTask(targetButtonId);
}
else {
taskInstance.deleteTask(targetButtonId);
}
}
// Attach event listener to document
function attachEventListeners() {
// For checkboxes
document.addEventListener("change", handleCheckboxChange);
// For all delete buttons
const buttons = document.querySelectorAll('.delete-task-button');
buttons.forEach(button => {button.addEventListener('click', handleDeleteButtons)});
}
//TEMPORARY
// const deleteBtn = document.getElementById("delete-button");
// deleteBtn.addEventListener("click", function() {
// taskInstance.deleteAllTask();
// });
document.addEventListener("DOMContentLoaded", function() {
attachEventListeners();
});