This commit is contained in:
2026-04-21 15:45:25 +08:00
parent a49eb4e77c
commit e50a6c91e6
10 changed files with 299 additions and 291 deletions

View File

@@ -1,170 +1,235 @@
// GLOBALS
const $taskForm = document.getElementById('taskForm');
const $toDoList = document.getElementById('toDoList');
const $completedList = document.getElementById('completedList');
const taskForm = document.getElementById('taskForm');
const toDoList = document.getElementById('toDoList');
const completedList = document.getElementById('completedList');
const url = "http://localhost:3001";
// RESET FORM
function resetForm() {
$taskForm.reset();
};
taskForm.reset();
}
// EVENT LISTENERS
const sortButton = document.getElementById("sortSelect");
window.addEventListener("DOMContentLoaded", () => {
displayTasks();
sortButton.value = "default";
});
sortButton.addEventListener('change', () => {
displayTasks();
});
$taskForm.addEventListener("submit", (event) => {
event.preventDefault();
createNewTask();
window.addEventListener("DOMContentLoaded", () => {
displayTasks();
});
[$toDoList, $completedList].forEach(list => {
list.addEventListener("click", (event) => {
if (
event.target.classList.contains("done") ||
event.target.classList.contains("notDone")
) {
toggleTaskStatus(event.target.dataset.id);
}
else if (event.target.classList.contains("delete")) {
deleteTask(event.target.dataset.id);
}
});
taskForm.addEventListener("submit", (event) => {
event.preventDefault();
createNewTask();
});
// EXAMPLE API
// async function exampleAPI() {
// const response = await fetch("http://localhost:3001/test");
// const data = await response.text();
// console.log(data);
// }
//
// exampleAPI();
// DISPLAY TASKS
async function displayTasks() {
const response = await fetch("http://localhost:3001/api/tasks")
if (!response.ok) {
throw new Error(`Failed to get tasks: ${response.status}`);
[toDoList, completedList].forEach(list => {
list.addEventListener('click', (event) => {
if (event.target.classList.contains("done")) {
const taskId = event.target.getAttribute("data-id");
completeTask(taskId);
}
else if (event.target.classList.contains("notDone")) {
const taskId = event.target.getAttribute("data-id");
taskNotCompleted(taskId);
}
else if (event.target.classList.contains("delete")) {
const taskId = event.target.getAttribute("data-id");
deleteTask(taskId);
}
else if (event.target.classList.contains('edit')) {
const task = {
id: event.target.getAttribute('data-id'),
title: event.target.getAttribute('data-title'),
description: event.target.getAttribute('data-description'),
dueDate: new Date(event.target.getAttribute('data-due-date'))
};
const modal = {
titleInput: document.getElementById('editTaskName'),
descriptionInput: document.getElementById('editTaskDescription'),
dueDateInput: document.getElementById('editDueDate'),
saveButton: document.getElementById('saveButton')
};
modal.titleInput.value = task.title;
modal.descriptionInput.value = task.description;
modal.dueDateInput.value = task.dueDate.toISOString().split('T')[0];
modal.saveButton.addEventListener('click', async () => {
await editTask(task.id);
bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
}, { once: true });
}
});
});
async function displayTasks() {
const sortSelect = document.getElementById('sortSelect');
const sortBy = sortSelect.value;
let query = '';
if (sortBy !== 'default') {
query = `?sortBy=${sortBy}`;
}
try {
const response = await fetch(`${url}/api/tasks${query}`);
if (!response.ok) {
throw new Error(`Failed to get tasks: ${response.status}`);
}
const data = await response.json();
try {
function formatTask(task) {
const li = document.createElement("li");
li.classList.add('card', 'p-3', 'mt-2');
const done = task.completed
? "text-decoration-line-through opacity-50"
: "";
li.innerHTML = `
<div class="d-flex justify-content-between align-items-start">
<h4 class="${done} col-11">${task.title}</h4>
<button data-id="${task.id}" type="button" class="btn-close delete" aria-label="Close"></button>
</div>
<p class="${done}">${task.description}</p>
<p class="${done}"><strong>Due: </strong>${task.dueDate}</p>
<div class="d-flex justify-content-between align-items-end">
<div>
${task.completed
? `<button data-id="${task.id}" class="btn btn-primary shadow-sm notDone" type="button">Not done</button>`
: `
<button data-id="${task.id}" class="btn btn-primary shadow-sm edit" type="button">Edit</button>
<button data-id="${task.id}" class="btn btn-primary shadow-sm done" type="button">Done</button>
`
}
</div>
<p class="m-0 ${done}"><strong>Created on: </strong>${task.dateCreated}</p>
</div>
`;
return li;
function formatTask(task) {
const li = document.createElement("li");
li.classList.add("card", "p-3", "shadow-sm", "mt-2");
const done = task.completed ? "text-decoration-line-through opacity-50" : "";
li.innerHTML = `
<div class="d-flex justify-content-between align-items-start">
<h4 class="${done} col-11">${task.title}</h4>
<button data-id="${task._id}" type="button" class="btn-close delete" aria-label="Close"></button>
</div>
<p class="${done}">${task.description}</p>
<p class="${done}"><strong>Due: </strong>${new Date(task.dueDate).toLocaleDateString()}</p>
<div class="d-flex justify-content-between align-items-end">
<div>
${task.completed ?
`<button data-id="${task._id}" class="btn btn-primary shadow-sm notDone" type="button">Not done</button>`
:
`
<button data-bs-toggle="modal" data-bs-target="#editModal" data-title="${task.title}" data-description="${task.description}" data-due-date="${task.dueDate}" data-id="${task._id}" class="btn btn-primary shadow-sm edit" type="button">Edit</button>
<button data-id="${task._id}" class="btn btn-primary shadow-sm done" type="button">Done</button>
`
}
$toDoList.innerHTML = "";
$completedList.innerHTML = "";
const tasks = Array.isArray(data) ? data : [];
if (!Array.isArray(data)) {
console.error("ERROR: Expected an array of tasks from /api/tasks", data);
}
tasks.forEach(task => {
const formattedTask = formatTask(task);
task.completed
? $completedList.appendChild(formattedTask)
: $toDoList.appendChild(formattedTask)
})
resetForm();
} catch (error) {
console.error(`ERROR: ${error}`);
</div>
<p class="m-0 ${done}"><strong>Created on: </strong>${new Date(task.dateCreated).toLocaleDateString()}</p>
</div>
`;
return li;
}
toDoList.innerHTML = "";
completedList.innerHTML = "";
const tasks = data;
tasks.forEach(task => {
const formattedTask = formatTask(task);
task.completed ? completedList.appendChild(formattedTask) : toDoList.appendChild(formattedTask);
});
resetForm();
} catch (error) {
console.error("Error: ", error);
}
}
async function createNewTask() {
const taskDetails = {
title: $taskForm.taskName.value.trim(),
description: $taskForm.taskDescription.value.trim(),
dueDate: $taskForm.dueDate.value,
}
if (!taskDetails.title || !taskDetails.description || !taskDetails.dueDate) {
alert("Please fill in all fields");
return;
}
try {
const response = await fetch("http://localhost:3001/api/tasks/todo", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(taskDetails)
});
if (!response.ok) {
throw new Error(`Failed to create task: ${response.status}`);
}
const data = await response.json();
console.log("Task created:", data);
displayTasks();
}
catch (error) {
console.error(`ERROR: ${error}`);
}
};
function toggleTaskStatus(taskId) {
const task = tasks.find(task => task.id === Number(taskId));
if (task) {
task.completed = !task.completed;
displayTasks();
const taskDetails = {
title: taskForm.taskName.value.trim(),
description: taskForm.taskDescription.value.trim(),
dueDate: taskForm.dueDate.value
}
if (!taskDetails.title || !taskDetails.description || !taskDetails.dueDate) {
return alert("All fields required!");
}
try {
const response = await fetch(`${url}/api/tasks/todo`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(taskDetails)
});
if (!response.ok) {
throw new Error(`Failed to post task: ${response.status}`);
}
const data = await response.json();
console.log(data);
displayTasks();
} catch (error) {
console.error("Error:", error);
}
}
function deleteTask(taskId) {
const taskIndex = tasks.findIndex(task => task.id == taskId);
if (taskIndex !== -1) {
tasks.splice(taskIndex, 1);
async function completeTask(taskId) {
try {
const response = await fetch(`${url}/api/tasks/complete/${taskId}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ completed: true })
});
if (!response.ok) {
throw new Error(`Failed to complete task: ${response.status}`);
}
const data = await response.json();
console.log("Task completed:", data);
displayTasks();
}
catch (error) {
console.error("Error:", error);
}
};
async function taskNotCompleted(taskId) {
try {
const response = await fetch(`${url}/api/tasks/notComplete/${taskId}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ completed: false })
});
if (!response.ok) {
throw new Error(`Failed to make task incomplete: ${response.status}`);
}
const data = await response.json();
console.log("Task not complete:", data);
displayTasks();
}
} catch (error) {
console.error("Error:", error);
}
};
async function deleteTask(taskId) {
try {
const response = await fetch(`${url}/api/tasks/delete/${taskId}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json"
}
});
if (!response.ok) {
throw new Error(`Failed to delete task: ${response.status}`);
}
const data = await response.json();
console.log({ message: "Deleted Task:", Task: data });
displayTasks();
function convertDate(dateString) {
return new Date(dateString).toLocaleDateString("en-AU");
}
} catch (error) {
console.error("Error:", error);
}
};
async function editTask(taskId) {
const updatedDetails = {
title: document.getElementById('editTaskName').value.trim(),
description: document.getElementById('editTaskDescription').value.trim(),
dueDate: document.getElementById('editDueDate').value
};
if (!updatedDetails.title || !updatedDetails.description || !updatedDetails.dueDate) {
return alert("All fields required!");
}
try {
const response = await fetch(`${url}/api/tasks/update/${taskId}`, {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(updatedDetails)
});
if (!response.ok) {
throw new Error(`Failed to edit task: ${response.status}`);
}
const data = await response.json();
console.log("Edited Task:", data);
displayTasks();
} catch (error) {
console.error("Error:", error);
}
};