Represents a single Todo item.
/
export class Todo {
/*
Creates a new Todo instance.
@param {string} title – The title of the todo.
@param {string} [description=''] – The description of the todo.
@param {string} dueDate – The due date of the todo in YYYY-MM-DD format.
@param {string} priority – The priority level ('low', 'medium', 'high').
@param {string} [notes=''] – Additional notes for the todo.
@param {string} [id] – Unique identifier for the todo.
*/
constructor(title, description = '', dueDate, priority, notes = '', id = uuidv4()) {
// Data Validation
if (!title || typeof title !== 'string') {
throw new Error('Title is required and must be a string.');
}
if (!dueDate || isNaN(dueDate) || !(dueDate instanceof Date)) {
throw new Error('A valid Due Date is required');
}
if (!Object.values(PRIORITY_LEVELS).includes(priority)) {
throw new Error(Priority must be one of ${Object.values(PRIORITY_LEVELS).join(', ')}.);
}
this.id = id; // Robust unique ID generation
this.title = title;
this.description = description;
this.dueDate = new Date(dueDate);
this.priority = priority;
this.notes = notes;
this.completed = false; // Track completion status
this.subtasks = []; // Array to hold subtasks if needed
this.recurrence = null; // For recurring tasks
this.checklist = [];
}
/**
Toggle the completion status of todo
*/
toggleCompletion() {
this.completed = !this.completed;
return this;
}
/**
Add a subtask to the todo.
@param {Todo} subtask – The subtask to add.
*/
addSubtask(subtask) {
if (subtask instanceof Todo) {
this.subtasks.push(subtask);
} else {
throw new Error('Subtask must be an instance of Todo.');
}
}
/**
Remove a subtask from the todo by ID.
@param {string} subtaskId – The ID of the subtask to remove.
*/
removeSubtask(subtaskId) {
this.subtasks = this.subtasks.filter((st) => st.id !== subtaskId);
}
}
// project.js
import { Todo } from './todo.js';
/**
Assistant
Represents a project containing multiple todos.
/
export class Project {
/*
Creates a new Project instance.
@param {string} name – The name of the project.
*/
constructor(name) {
if (!name || typeof name !== 'string') {
throw new Error('Project name is required and must be a string.');
}
this.name = name;
/** @type {Todo[]} */
this.todos = []; // Array to hold todos
}
/**
Add a new Todo to the project.
@param {Todo} todo – The todo instance to add.
@returns {boolean} True if added successfully, false otherwise.
*/
addTodo(todo) {
if (todo instanceof Todo) {
this.todos.push(todo);
return true;
} else {
console.error('Only instances of Todo can be added.');
return false;
}
}
/**
Remove a todo by its ID
@param {*} todoId
*/
removeTodo(todoId) {
const initialLength = this.todos.length;
this.todos = this.todos.filter((t) => t.id !== todoId); // Remove the todo
if (this.todos.length === initialLength) {
console.warn(Todo with ID ${todoId} not found);
}
}
/**
Get a todo by its ID
@param {string} todoId – The ID of the todo to retrieve.
@returns {Todo|null} The todo instance or null if not found
*/
getTodoById(todoId) {
return this.todos.find((t) => t.id === todoId) || null;
}
/**
Update a todo's details
@param {Todo} updatedTodo – The updated Todo instance.
@returns {boolean} True if updated successfully, false otherwise.
*/
updateTodo(updatedTodo) {
const index = this.todos.findIndex((t) => t.id === updatedTodo.id);
if (index !== -1) {
this.todos[index] = updatedTodo;
return true;
} else {
console.error(Todo with ID ${updatedTodo.id} not found);
return false;
}
}
/**
Toggle completion status of a todo by its ID.
@param {string} todoId – The ID of the todo to toggle.
@returns {boolean} True if toggled successfully, false otherwise.
*/
toggleTodoCompletion(todoId) {
const todo = this.getTodoById(todoId);
if (todo) {
todo.toggleCompletion();
return true;
} else {
console.error(Todo with ID ${todoId} not found);
return false;
}
}
@returns {Project[]} Array of Project instances.
*/
static loadProjects() {
try {
const serializedProjects = localStorage.getItem('projects');
if (!serializedProjects) return [];
code
const projectsData = JSON.parse(serializedProjects);
return projectsData.map((projectData) => {
const project = new Project(projectData.name);
project.todos = Array.isArray(projectData.todos) ? projectData.todos.map((todoData) => {
// Validate dueDate
if (!todoData.dueDate || isNaN(Date.parse(todoData.dueDate))) {
console.error(`Invalid due date for todo: ${todoData.dueDate}`);
}
const todo = new Todo(
todoData.title,
todoData.description,
new Date(todoData.dueDate),
todoData.priority,
todoData.notes,
todoData.id // Pass the existing ID
);
todo.completed = todoData.completed;
todo.subtasks = Array.isArray(todoData.subtasks) ? todoData.subtasks.map((subtaskData) => {
return new Todo(
subtaskData.title,
subtaskData.description,
subtaskData.dueDate,
subtaskData.priority,
subtaskData.notes,
subtaskData.id
);
})
: [];
todo.recurrence = todoData.recurrence || null;
return todo;
})
: [];
return project;
});
} catch (error) {
console.error('Failed to load projects from localStorage:', error);
// Optional: clean corrupted data
localStorage.removeItem('projects');
alert('Stored data was corrupted and has been reset.');
// Return an empty array or default projects
return [];
}
}
}
// index.js
import './style.css';
import { initializeApp } from './app.js';
import { initializeUI, setupEventListeners } from './ui.js';
function init() {
// Initialize the application
initializeApp();
code
// Initialize UI interactions
initializeUI();
// Set up event listeners
setupEventListeners();
}
// Initialize the application on DOMContentLoaded
document.addEventListener('DOMContentLoaded', init);
// ui.js
import { getCurrentProject, getState, setCurrentProjectIndex, updateTodo } from "./app";
import { StorageManager } from "./localStorage";
// import { Project } from "./project";
import { Todo } from "./todo";
@param {number} index – Index of the selected project.
*/
function highlightSelectedProject(index) {
const items = document.querySelectorAll('#project-list li')
items.forEach((item, i) => {
item.classList.toggle('selected', i === index);
});
}
/**
Render the todos for the selected project.
@param {Project} project – The Project instance whose todos are to be rendered.
*/
export function renderTodos(project) {
const todoContainer = document.querySelector("#todo-container");
todoContainer.innerHTML = ""; // Clear existing todos
if (!project || !project.todos) {
console.error("Invalid project or no todos available");
return;
}
@param {Todo} todo – The todo item to create an element for.
@returns {HTMLElement} The DOM element representing the todo.
*/
function createTodoElement(todo) {
const todoElement = document.createElement('div');
todoElement.classList.add('todo-item', priority-${todo.priority});
todoElement.dataset.id = todo.id
// Todo title and Due Date
const todoInfo = document.createElement('span');
todoInfo.textContent = ${todo.title} – Due: ${todo.dueDate};
todoInfo.classList.add('todo-info');
todoElement.appendChild(todoInfo);
Set up interactions for todo items (edit, delete).
*/
export function setupTodoInteraction() {
const todoContainer = document.querySelector('#todo-container');
// Handle edit and delete buttons using event delegation
todoContainer.addEventListener('click', (event) => {
const target = event.target;
const todoElement = target.closest('.todo-item');
if (!todoElement) return;
code
const todoId = todoElement.getAttribute('data-id');
const currentProject = getCurrentProject();
const todo = currentProject.getTodoById(todoId);
if (!todo) {
console.error(`Todo with ID: ${todoId} not found`)
return;
}
if (target.matches('.edit-button')) {
showEditForm(todo, currentProject);
}
if (target.matches('.delete-button')) {
handleDeleteTodo(todoId, currentProject);
}
});
}
/**
Handle deleting a todo.
@param {string} todoId – ID of the todo to delete.
@param {Project} project – The project containing the todo.
*/
function handleDeleteTodo(todoId, project) {
if (confirm('Are you sure you want to delete this task?')) {
project.removeTodo(todoId);
StorageManager.saveProjects(getState().projects);
renderTodos(project);
}
}
/**
Show the edit form modal with the current task data.
@param {Todo} todo – The todo to edit.
*/
function showEditForm(todo) {
// Fill in the form with current todo data
document.querySelector("#edit-title").value = todo.title;
document.querySelector("#edit-description").value = todo.description;
document.querySelector("#edit-due-date").value = todo.dueDate;
document.querySelector("#edit-priority").value = todo.priority;
const modal = document.querySelector("#edit-task-modal");
if (!modal) {
console.error("Edit Task Modal not found in the DOM");
return;
}
// Close modal when clicking the close button
document.querySelector('.close-button').onclick = () => {
closeModal();
};
// Close modal when clicking outside of the modal control
window.addEventListener("click", (event) => {
if (event.target === modal) {
closeModal();
}
});
}
/**
Handle saving changes to a todo.
@param {Todo} todo – The todo being edited.
*/
const saveChangesHandler = (todo) => {
const updatedTitle = document.querySelector("#edit-title").value.trim();
const updatedDescription = document.querySelector("#edit-description").value.trim();
const updatedDueDate = document.querySelector("#edit-due-date").value;
const updatedPriority = document.querySelector("#edit-priority").value;
code
if (!updatedTitle || !updatedDueDate) {
alert("Title and Due Date are required.");
return;
}
// Update todo properties
todo.title = updatedTitle;
todo.description = updatedDescription;
todo.dueDate = updatedDueDate;
todo.priority = updatedPriority;
try {
updateTodo(todo); // Update in state and save
closeModal();
} catch (error) {
console.error("Error updating todo:", error);
}
closeModal();
}
/**
Function to close the edit modal.
*/
function closeModal() {
const modal = document.querySelector('#edit-task-modal');
if (modal) {
modal.style.display = "none";
modal.setAttribute('aria-hidden', 'true');
document.body.classList.remove('modal-open');
}
Set up closing the modal when Esc key is pressed.
*/
function setupModalCloseOnEscape() {
const modal = document.querySelector('#edit-task-modal');
window.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && modal.style.display !== 'none') {
closeModal();
}
});
}
/**
Function to handle adding a new todo.
*/
function handleAddTodo() {
try {
const title = document.querySelector('#todo-title').value;
const description = document.querySelector('#todo-description').value;
const dueDate = document.querySelector('#todo-due-date').value;
const priority = document.querySelector('#todo-priority').value;
code
if (title && dueDate) { // Ensure title and due date are provided
addTodo(title, description, dueDate, priority); // Call function to add a new todo
clearTodoInputs();
} else {
showAlert('Please fill in both title and due date.'); // Alert if fields are empty
}
Function to handle adding a new project.
*/
function handleAddProject() {
try {
const projectName = document.querySelector('#project-name').value.trim();
code
// Call function to add a new project
if (projectName) {
addProject(projectName);
document.querySelector('#project-name').value = ''; // Clear input field
} else {
showAlert('Please enter a project name.') // Alert if project name is empty
}
Function to clear todo input fields
*/
function clearTodoInputs() {
document.querySelector('#todo-title').value = ''; // Clear input field after adding
document.querySelector('#todo-description').value = '';
document.querySelector('#todo-due-date').value = '';
document.querySelector('#todo-priority').value = 'low'; // Reset priority to default
}
// Function to show alert messages
function showAlert(message) {
const alertBox = document.createElement('div');
alertBox.classList.add('alert');
alertBox.textContent = message;
Set up event listeners for the application.
*/
export function setupEventListeners() {
document.addEventListener('click', (event) => {
if (event.target.matches('#add-todo-button')) {
handleAddTodo();
}
if (event.target.matches('#add-project-button')) {
handleAddProject();
}
code
// Handle modal close actions
if (event.target.matches('.close-button') || event.target.matches('#cancel-button')) {
closeModal();
}
import { Project } from './project.js';
import { Todo } from './todo.js';
import { StorageManager } from './localStorage.js';
import { renderTodos, renderProjects } from './ui.js';
/**
Application state encapsulated in an object.
/
const state = {
/* @type {Project[]} /
projects: [],
/* @type {number} */
currentProjectIndex: 0
};
/**
Getter for the application state.
@returns {Object} The current state.
*/
export function getState() {
return { ...state }; // Return a shallow copy to prevent direct mutation.
}
/**
Returns a shallow copy of the projects array. To prevent mutations.
@returns {Object[]} Array of Project instances.
*/
export function getProjects() {
return [...state.projects];
}
/**
Gets the index of the current project.
@returns {number} The current project index.
*/
export function getCurrentProjectIndex() {
return state.currentProjectIndex;
}
/**
Gets the current project instance.
@returns {Project} The current project.
*/
export function getCurrentProject() {
return state.projects[state.currentProjectIndex];
}
/**
Sets the current project index and renders its todos.
@param {number} index – The index of the project to set as current.
*/
export function setCurrentProjectIndex(index) {
if (index >= 0 && index < state.projects.length) {
state.currentProjectIndex = index;
renderTodos(state.projects[index]);
} else {
console.error('Invalid project index.');
}
}
Initializes the application by loading projects and rendering them.
*/
export function initializeApp() {
// Load existing projects from localStorage on startup
const loadedProjects = StorageManager.loadProjects();
if (loadedProjects.length > 0) {
state.projects = loadedProjects;
} else {
// Create a default project if none exist
const defaultProject = new Project('Default Project');
state.projects.push(defaultProject);
StorageManager.saveProjects(state.projects);
}
// Render the loaded or default projects
renderProjects(state.projects);
// renderTodos(getCurrentProject());
setCurrentProjectIndex(0);
}
/**
Adds a new todo to the current project
@param {string} title – The title of the todo.
@param {string} description – The description of the todo.
@param {string} dueDate – The due date of the todo.
@param {string} priority – The priority of the todo.
*/
export function addTodo(title, description, dueDate, priority) {
const currentProject = getCurrentProject(); // Use selected project
if (!currentProject) {
console.error('No current project selected');
return;
}
try {
const newTodo = new Todo(title, description, dueDate, priority);
currentProject.addTodo(newTodo);
// Save updated projects to localStorage
StorageManager.saveProjects(state.projects);
code
// Render todos for the current project
renderTodos(currentProject);
} catch (error) {
console.error('Error adding todo:', error);
}
// return newTodo; // Return the created Todo object
}
/**
Adds a new project to the application.
@param {string} projectName – The name of the new project.
*/
export function addProject(projectName) {
if (!projectName || typeof projectName !== 'string') {
console.error('Invalid project name');
return;
}
try {
const newProject = new Project(projectName);
state.projects.push(newProject);
// Save updated projects to localStorage
StorageManager.saveProjects(state.projects);
// Re-render the projects list
renderProjects(state.projects);
} catch (error) {
console.error('Error adding project:', error);
}
}
// Function to update a todo
/**
Updates the existing todo in the current project.
@param {Todo} updatedTodo – The todo instance with updated details.
@returns
*/
export function updateTodo(updatedTodo) {
const currentProject = getCurrentProject();
if (!currentProject) {
console.error('No current project selected.');
return;
}
/* Modal Styling /
.modal {
display: none; / Hidden by default /
position: fixed; / Stay in place /
z-index: 1000; / Sit on top /
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto; / Enable scroll if needed /
/ background-color: rgb(0, 0, 0); Fallback color /
background-color: var(--modal-background) / Black w/ opacity */
}
.modal-content {
background-color: #fefefe;
margin: 10% auto; /* 10% from the top and centered /
padding: 1.25rem;
border: 1px solid #888;
width: 90%; / Could be more or less, depending on screen size /
max-width: 31.25rem; / 500px */
border-radius: 0.3125rem;
As an expert developer and tutor, I'd be happy to review your code and provide suggestions for improvements.
Overall Assessment:
Your code demonstrates a solid understanding of JavaScript, ES6 modules, and object-oriented programming principles. The separation of concerns between different modules (todo.js, project.js, localStorage.js, etc.) is well-handled, and the use of classes like Todo, Project, and StorageManager is appropriate. Additionally, the use of JSDoc comments enhances readability and maintainability.
However, there are some areas where improvements can be made:
Data Validation:
Issue: In todo.js, the validation for dueDate is incorrect. The checks isNaN(dueDate) and !(dueDate instanceof Date) are not appropriate since dueDate is expected to be a string in 'YYYY-MM-DD' format.
Improvement: Validate dueDate by parsing it with Date.parse and checking if the result is a valid date.
Event Handling and Scope:
Issue: In ui.js, the event listener for saving changes in showEditForm is set up incorrectly, leading to potential multiple handlers being added every time the form is opened.
Improvement: Define event handler functions within the scope where they're used and ensure they're properly added and removed to prevent memory leaks or unintended behavior.
Module Imports:
Issue: Functions like addTodo and addProject are used in ui.js but are not imported from app.js.
Improvement: Import the necessary functions from the modules where they are defined.
Consistency and Code Style:
Issue: Inconsistent use of function declarations and expressions can lead to confusion.
Improvement: Adopt a consistent coding style throughout the codebase.
Error Handling:
Issue: In several places, errors are logged but not handled, which may make debugging difficult.
Improvement: Implement proper error handling strategies, such as displaying user-friendly messages or fallbacks.
HTML and Scripts Inclusion:
Issue: In index.html, the script tags for including JavaScript files are commented out, preventing the app from running.
Improvement: Include the necessary script tags with the correct type attribute.
Below are the improved versions of your files with the suggested enhancements.
todo.js
javascript
// todo.js
import { v4 as uuidv4 } from 'uuid'; // Ensure you have installed the `uuid` package via npm
const PRIORITY_LEVELS = {
LOW: 'low',
MEDIUM: 'medium',
HIGH: 'high',
};
/**
* Represents a single Todo item.
*/
export class Todo {
/**
* Creates a new Todo instance.
* @param {string} title – The title of the todo.
* @param {string} [description=''] – The description of the todo.
* @param {string} dueDate – The due date of the todo in YYYY-MM-DD format.
* @param {string} priority – The priority level ('low', 'medium', 'high').
* @param {string} [notes=''] – Additional notes for the todo.
* @param {string} [id] – Unique identifier for the todo.
*/
constructor(title, description = '', dueDate, priority, notes = '', id = uuidv4()) {
// Data Validation
if (!title || typeof title !== 'string') {
throw new Error('Title is required and must be a string.');
}
if (!dueDate || isNaN(Date.parse(dueDate))) {
throw new Error('A valid Due Date is required.');
}
if (!Object.values(PRIORITY_LEVELS).includes(priority)) {
throw new Error(`Priority must be one of ${Object.values(PRIORITY_LEVELS).join(', ')}.`);
}
this.id = id; // Robust unique ID generation
this.title = title;
this.description = description;
this.dueDate = new Date(dueDate);
this.priority = priority;
this.notes = notes;
this.completed = false; // Track completion status
this.subtasks = []; // Array to hold subtasks if needed
this.recurrence = null; // For recurring tasks
this.checklist = [];
}
/**
* Toggle the completion status of todo
*/
toggleCompletion() {
this.completed = !this.completed;
return this;
}
/**
* Add a subtask to the todo.
* @param {Todo} subtask – The subtask to add.
*/
addSubtask(subtask) {
if (subtask instanceof Todo) {
this.subtasks.push(subtask);
} else {
throw new Error('Subtask must be an instance of Todo.');
}
}
/**
* Remove a subtask from the todo by ID.
* @param {string} subtaskId – The ID of the subtask to remove.
*/
removeSubtask(subtaskId) {
this.subtasks = this.subtasks.filter((st) => st.id !== subtaskId);
}
}
Improvements:
Corrected the due date validation using Date.parse(dueDate).
Ensured that this.dueDate is properly set as a Date object.
project.js
javascript
// project.js
import { Todo } from './todo.js';
/**
* Represents a project containing multiple todos.
*/
export class Project {
/**
* Creates a new Project instance.
* @param {string} name – The name of the project.
*/
constructor(name) {
if (!name || typeof name !== 'string') {
throw new Error('Project name is required and must be a string.');
}
this.name = name;
/** @type {Todo[]} */
this.todos = []; // Array to hold todos
}
/**
* Add a new Todo to the project.
* @param {Todo} todo – The todo instance to add.
* @returns {boolean} True if added successfully, false otherwise.
*/
addTodo(todo) {
if (todo instanceof Todo) {
this.todos.push(todo);
return true;
} else {
console.error('Only instances of Todo can be added.');
return false;
}
}
/**
* Remove a todo by its ID.
* @param {string} todoId – The ID of the todo to remove.
*/
removeTodo(todoId) {
const initialLength = this.todos.length;
this.todos = this.todos.filter((t) => t.id !== todoId); // Remove the todo
if (this.todos.length === initialLength) {
console.warn(`Todo with ID ${todoId} not found.`);
}
}
/**
* Get a todo by its ID.
* @param {string} todoId – The ID of the todo to retrieve.
* @returns {Todo|null} The todo instance or null if not found.
*/
getTodoById(todoId) {
return this.todos.find((t) => t.id === todoId) || null;
}
/**
* Update a todo's details.
* @param {Todo} updatedTodo – The updated Todo instance.
* @returns {boolean} True if updated successfully, false otherwise.
*/
updateTodo(updatedTodo) {
const index = this.todos.findIndex((t) => t.id === updatedTodo.id);
if (index !== -1) {
this.todos[index] = updatedTodo;
return true;
} else {
console.error(`Todo with ID ${updatedTodo.id} not found.`);
return false;
}
}
/**
* Toggle completion status of a todo by its ID.
* @param {string} todoId – The ID of the todo to toggle.
* @returns {boolean} True if toggled successfully, false otherwise.
*/
toggleTodoCompletion(todoId) {
const todo = this.getTodoById(todoId);
if (todo) {
todo.toggleCompletion();
return true;
} else {
console.error(`Todo with ID ${todoId} not found.`);
return false;
}
}
/**
* Get all completed todos.
* @returns {Todo[]} Array of completed todos.
*/
getCompletedTodos() {
return this.todos.filter((todo) => todo.completed);
}
}
Improvements:
Minor formatting adjustments.
Ensured consistent punctuation in console messages.
localStorage.js
javascript
// localStorage.js
import { Project } from './project.js';
import { Todo } from './todo.js';
/**
* Manages saving and loading projects to and from localStorage.
*/
export class StorageManager {
/**
* Save projects to localStorage.
* @param {Project[]} projects – Array of Project instances.
*/
static saveProjects(projects) {
try {
const serializedProjects = JSON.stringify(projects);
localStorage.setItem('projects', serializedProjects);
} catch (error) {
console.error('Error saving to localStorage:', error);
}
}
/**
* Loads projects from localStorage.
* @returns {Project[]} Array of Project instances.
*/
static loadProjects() {
try {
const serializedProjects = localStorage.getItem('projects');
if (!serializedProjects) return [];
const projectsData = JSON.parse(serializedProjects);
return projectsData.map((projectData) => {
const project = new Project(projectData.name);
project.todos = Array.isArray(projectData.todos)
? projectData.todos.map((todoData) => {
// Validate dueDate
if (!todoData.dueDate || isNaN(Date.parse(todoData.dueDate))) {
console.error(`Invalid due date for todo: ${todoData.dueDate}`);
}
const todo = new Todo(
todoData.title,
todoData.description,
todoData.dueDate,
todoData.priority,
todoData.notes,
todoData.id // Pass the existing ID
);
todo.completed = todoData.completed;
todo.subtasks = Array.isArray(todoData.subtasks)
? todoData.subtasks.map((subtaskData) => {
return new Todo(
subtaskData.title,
subtaskData.description,
subtaskData.dueDate,
subtaskData.priority,
subtaskData.notes,
subtaskData.id
);
})
: [];
todo.recurrence = todoData.recurrence || null;
return todo;
})
: [];
return project;
});
} catch (error) {
console.error('Failed to load projects from localStorage:', error);
// Optional: clean corrupted data
localStorage.removeItem('projects');
alert('Stored data was corrupted and has been reset.');
// Return an empty array or default projects
return [];
}
}
}
Improvements:
Corrected mismatched braces and indentation issues.
Ensured that new Date is appropriately handled in Todo constructor.
index.js
javascript
// index.js
import './style.css';
import { initializeApp } from './app.js';
import { initializeUI, setupEventListeners } from './ui.js';
function init() {
// Initialize the application
initializeApp();
// Initialize UI interactions
initializeUI();
// Set up event listeners
setupEventListeners();
}
// Initialize the application on DOMContentLoaded
document.addEventListener('DOMContentLoaded', init);
Improvements:
No changes needed; the file is concise and functional.
ui.js
javascript
Improvements:
Event Handling:
Defined event handlers within the scope of showEditForm to properly manage event listeners.
Removed event listeners appropriately to prevent memory leaks.
Module Imports:
Added imports for addTodo and addProject from app.js.
Consistency:
Used function declarations consistently.
Date Handling:
Ensured dates are formatted correctly when displaying and editing.
app.js
No major changes needed; your app.js is well-structured and functional.
index.html
html
Improvements:
Uncommented and corrected the script tag to include index.js with type="module".
Ensured that the paths to CSS and JS files are correct.
Added type="button" to buttons inside forms to prevent unintended form submission.
style.css
No significant changes were needed in your CSS file, as it styles the application appropriately.
Conclusion:
By addressing the highlighted issues, the application should function more reliably and be easier to maintain. Remember to test each component thoroughly after making changes to ensure everything works as expected.
If you have any questions or need further clarification on any of the changes, feel free to ask!
Not yet included in a published release.
// ui.js
import {
getCurrentProject,
getState,
setCurrentProjectIndex,
updateTodo,
addTodo,
addProject,
} from './app';
import { StorageManager } from './localStorage';
import { Todo } from './todo';
/**
* Render the list of projects in the sidebar.
* @param {Array} projects - Array of Project instances.
*/
export function renderProjects(projects) {
const projectContainer = document.querySelector('#project-list');
projectContainer.innerHTML = ''; // Clear existing projects
projects.forEach((project, index) => {
const projectElement = document.createElement('li');
projectElement.textContent = project.name;
projectElement.classList.add('project-item');
projectElement.setAttribute('data-index', index);
projectElement.setAttribute('tabindex', '0'); // Make focusable
projectContainer.appendChild(projectElement);
});
highlightSelectedProject(getState().currentProjectIndex);
}
/**
* Highlight the selected project in the sidebar.
* @param {number} index – Index of the selected project.
*/
function highlightSelectedProject(index) {
const items = document.querySelectorAll('#project-list li');
items.forEach((item, i) => {
item.classList.toggle('selected', i === index);
});
}
/**
* Render the todos for the selected project.
* @param {Project} project – The Project instance whose todos are to be rendered.
*/
export function renderTodos(project) {
const todoContainer = document.querySelector('#todo-container');
todoContainer.innerHTML = ''; // Clear existing todos
if (!project || !project.todos) {
console.error('Invalid project or no todos available');
return;
}
project.todos.forEach((todo) => {
const todoElement = createTodoElement(todo);
todoContainer.appendChild(todoElement);
});
}
/**
* Create a DOM element for a single todo item.
* @param {Todo} todo – The todo item to create an element for.
* @returns {HTMLElement} The DOM element representing the todo.
*/
function createTodoElement(todo) {
const todoElement = document.createElement('div');
todoElement.classList.add('todo-item', `priority-${todo.priority}`);
todoElement.dataset.id = todo.id;
// Todo title and Due Date
const todoInfo = document.createElement('span');
todoInfo.textContent = `${todo.title} – Due: ${todo.dueDate.toDateString()}`;
todoInfo.classList.add('todo-info');
todoElement.appendChild(todoInfo);
// Edit button
const editButton = createButton('Edit', 'edit-button');
// Delete button
const deleteButton = createButton('Delete', 'delete-button');
todoElement.appendChild(editButton);
todoElement.appendChild(deleteButton);
// Apply priority-based styling
todoElement.classList.add(`priority-${todo.priority}`);
return todoElement;
}
function createButton(text, className) {
const button = document.createElement('button');
button.textContent = text;
button.classList.add(className);
return button;
}
/**
* Set up interactions for todo items (edit, delete).
*/
export function setupTodoInteraction() {
const todoContainer = document.querySelector('#todo-container');
// Handle edit and delete buttons using event delegation
todoContainer.addEventListener('click', (event) => {
const target = event.target;
const todoElement = target.closest('.todo-item');
if (!todoElement) return;
const todoId = todoElement.getAttribute('data-id');
const currentProject = getCurrentProject();
const todo = currentProject.getTodoById(todoId);
if (!todo) {
console.error(`Todo with ID: ${todoId} not found`);
return;
}
if (target.matches('.edit-button')) {
showEditForm(todo);
}
if (target.matches('.delete-button')) {
handleDeleteTodo(todoId, currentProject);
}
});
}
/**
* Handle deleting a todo.
* @param {string} todoId – ID of the todo to delete.
* @param {Project} project – The project containing the todo.
*/
function handleDeleteTodo(todoId, project) {
if (confirm('Are you sure you want to delete this task?')) {
project.removeTodo(todoId);
StorageManager.saveProjects(getState().projects);
renderTodos(project);
}
}
/**
* Show the edit form modal with the current task data.
* @param {Todo} todo – The todo to edit.
*/
function showEditForm(todo) {
// Fill in the form with current todo data
document.querySelector('#edit-title').value = todo.title;
document.querySelector('#edit-description').value = todo.description;
document.querySelector('#edit-due-date').value = todo.dueDate.toISOString().split('T')[0];
document.querySelector('#edit-priority').value = todo.priority;
const modal = document.querySelector('#edit-task-modal');
if (!modal) {
console.error('Edit Task Modal not found in the DOM');
return;
}
modal.style.display = 'block';
modal.setAttribute('aria-hidden', 'false');
modal.querySelector('#edit-title').focus();
document.body.classList.add('modal-open'); // Prevent background scrolling
const saveButton = document.querySelector('#save-changes-button');
const cancelButton = document.querySelector('#cancel-button');
const closeButton = document.querySelector('.close-button');
// Define event handlers
function saveChangesHandler() {
const updatedTitle = document.querySelector('#edit-title').value.trim();
const updatedDescription = document.querySelector('#edit-description').value.trim();
const updatedDueDate = document.querySelector('#edit-due-date').value;
const updatedPriority = document.querySelector('#edit-priority').value;
if (!updatedTitle || !updatedDueDate) {
alert('Title and Due Date are required.');
return;
}
// Update todo properties
todo.title = updatedTitle;
todo.description = updatedDescription;
todo.dueDate = new Date(updatedDueDate);
todo.priority = updatedPriority;
try {
updateTodo(todo); // Update in state and save
closeModal();
} catch (error) {
console.error('Error updating todo:', error);
}
}
function closeModal() {
modal.style.display = 'none';
modal.setAttribute('aria-hidden', 'true');
document.body.classList.remove('modal-open');
// Remove event listeners to prevent duplicate handlers
saveButton.removeEventListener('click', saveChangesHandler);
cancelButton.removeEventListener('click', closeModal);
closeButton.removeEventListener('click', closeModal);
window.removeEventListener('keydown', escKeyHandler);
window.removeEventListener('click', outsideClickHandler);
}
function escKeyHandler(event) {
if (event.key === 'Escape') {
closeModal();
}
}
function outsideClickHandler(event) {
if (event.target === modal) {
closeModal();
}
}
// Add event listeners
saveButton.addEventListener('click', saveChangesHandler);
cancelButton.addEventListener('click', closeModal);
closeButton.addEventListener('click', closeModal);
window.addEventListener('keydown', escKeyHandler);
window.addEventListener('click', outsideClickHandler);
}
/**
* Setup project selection interactions.
*/
export function setupProjectSelection() {
const projectContainer = document.querySelector('#project-list');
projectContainer.addEventListener('click', (event) => {
if (event.target && event.target.matches('li.project-item')) {
const index = parseInt(event.target.getAttribute('data-index'));
setCurrentProjectIndex(index);
highlightSelectedProject(index);
const currentProject = getState().projects[index];
renderTodos(currentProject);
}
});
// Accessibility: Allow selection via keyboard
projectContainer.addEventListener('keydown', (event) => {
if (event.key === 'Enter' && event.target.matches('li.project-item')) {
const index = parseInt(event.target.getAttribute('data-index'));
setCurrentProjectIndex(index);
highlightSelectedProject(index);
const currentProject = getState().projects[index];
renderTodos(currentProject);
}
});
}
/**
* Initialize UI interactions.
*/
export function initializeUI() {
setupProjectSelection();
setupTodoInteraction();
}
/**
* Function to handle adding a new todo.
*/
function handleAddTodo() {
try {
const title = document.querySelector('#todo-title').value;
const description = document.querySelector('#todo-description').value;
const dueDate = document.querySelector('#todo-due-date').value;
const priority = document.querySelector('#todo-priority').value;
if (title && dueDate) {
addTodo(title, description, dueDate, priority); // Call function to add a new todo
clearTodoInputs();
} else {
showAlert('Please fill in both title and due date.');
}
} catch (error) {
console.error('Error adding todo:', error);
}
}
/**
* Function to handle adding a new project.
*/
function handleAddProject() {
try {
const projectName = document.querySelector('#project-name').value.trim();
if (projectName) {
addProject(projectName);
document.querySelector('#project-name').value = ''; // Clear input field
} else {
showAlert('Please enter a project name.');
}
} catch (error) {
console.error('Error adding project:', error);
}
}
/**
* Function to clear todo input fields.
*/
function clearTodoInputs() {
document.querySelector('#todo-title').value = '';
document.querySelector('#todo-description').value = '';
document.querySelector('#todo-due-date').value = '';
document.querySelector('#todo-priority').value = 'low';
}
/**
* Function to show alert messages.
*/
function showAlert(message) {
const alertBox = document.createElement('div');
alertBox.classList.add('alert');
alertBox.textContent = message;
document.body.appendChild(alertBox);
setTimeout(() => {
alertBox.classList.add('fade-out');
alertBox.addEventListener('transitionend', () => {
alertBox.remove();
});
}, 3000);
}
/**
* Set up event listeners for the application.
*/
export function setupEventListeners() {
document.addEventListener('click', (event) => {
if (event.target.matches('#add-todo-button')) {
handleAddTodo();
}
if (event.target.matches('#add-project-button')) {
handleAddProject();
}
});
}