Web-based Smart Task Manager JavaScript, API

👤 Sharing: AI
```javascript
// Web-based Smart Task Manager (Client-Side - HTML & JavaScript)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Smart Task Manager</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        #task-form {
            margin-bottom: 20px;
        }

        #task-list {
            list-style: none;
            padding: 0;
        }

        .task-item {
            border: 1px solid #ccc;
            padding: 10px;
            margin-bottom: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .task-item span {
            flex-grow: 1; /* Allows task text to expand and fill available space */
        }

        .task-item button {
            margin-left: 10px;
        }

        .priority-low {
            background-color: #d4edda; /* Light green */
        }

        .priority-medium {
            background-color: #fff3cd; /* Light yellow */
        }

        .priority-high {
            background-color: #f8d7da; /* Light red */
        }

        #task-details {
          margin-top: 20px;
          border: 1px solid #ddd;
          padding: 10px;
          display: none; /* Initially hidden */
        }
    </style>
</head>
<body>

    <h1>Smart Task Manager</h1>

    <div id="task-form">
        <label for="task-name">Task Name:</label>
        <input type="text" id="task-name" required><br><br>

        <label for="task-description">Description:</label>
        <textarea id="task-description" rows="3"></textarea><br><br>

        <label for="task-priority">Priority:</label>
        <select id="task-priority">
            <option value="low">Low</option>
            <option value="medium">Medium</option>
            <option value="high">High</option>
        </select><br><br>

        <button onclick="addTask()">Add Task</button>
    </div>

    <h2>Task List</h2>
    <ul id="task-list">
        <!-- Tasks will be added here dynamically -->
    </ul>

    <div id="task-details">
      <h3>Task Details</h3>
      <p id="details-name"></p>
      <p id="details-description"></p>
      <p id="details-priority"></p>
      <button onclick="hideTaskDetails()">Close</button>
    </div>

    <script>
        let tasks = []; // Array to store task objects
        let nextTaskId = 1; // Simple ID generator

        function addTask() {
            const taskNameInput = document.getElementById("task-name");
            const taskDescriptionInput = document.getElementById("task-description");
            const taskPrioritySelect = document.getElementById("task-priority");

            const taskName = taskNameInput.value.trim(); // Trim to remove leading/trailing whitespace
            const taskDescription = taskDescriptionInput.value.trim();
            const taskPriority = taskPrioritySelect.value;

            if (taskName === "") {
                alert("Task name cannot be empty.");
                return;
            }

            const task = {
                id: nextTaskId++,
                name: taskName,
                description: taskDescription,
                priority: taskPriority,
                completed: false
            };

            tasks.push(task);
            renderTaskList();

            // Clear the form
            taskNameInput.value = "";
            taskDescriptionInput.value = "";
            taskPrioritySelect.value = "low";  // Reset to default
        }


        function renderTaskList() {
            const taskListElement = document.getElementById("task-list");
            taskListElement.innerHTML = ""; // Clear the existing list

            for (const task of tasks) {
                const listItem = document.createElement("li");
                listItem.classList.add("task-item");
                listItem.classList.add(`priority-${task.priority}`); // Add priority-based class

                listItem.innerHTML = `
                    <span>${task.name}</span>
                    <button onclick="showTaskDetails(${task.id})">Details</button>
                    <button onclick="completeTask(${task.id})">${task.completed ? 'Undo' : 'Complete'}</button>
                    <button onclick="deleteTask(${task.id})">Delete</button>
                `;

                taskListElement.appendChild(listItem);
            }
        }

        function completeTask(taskId) {
            const task = tasks.find(task => task.id === taskId);
            if (task) {
                task.completed = !task.completed; // Toggle completion status
                renderTaskList(); // Re-render the list to update the button text
            }
        }

        function deleteTask(taskId) {
            tasks = tasks.filter(task => task.id !== taskId); // Create a new array excluding the deleted task
            renderTaskList(); // Re-render the list
        }

        function showTaskDetails(taskId) {
          const task = tasks.find(task => task.id === taskId);
          if (!task) return;

          document.getElementById("details-name").textContent = `Name: ${task.name}`;
          document.getElementById("details-description").textContent = `Description: ${task.description}`;
          document.getElementById("details-priority").textContent = `Priority: ${task.priority}`;

          document.getElementById("task-details").style.display = "block"; // Show the details div
        }

        function hideTaskDetails() {
          document.getElementById("task-details").style.display = "none";
        }


        // Initial render (if any tasks are pre-loaded from local storage or server)
        renderTaskList();
    </script>

</body>
</html>
```

Key improvements and explanations:

* **Clearer HTML Structure:** The HTML is now well-structured with appropriate elements for form, list, and styling.  Uses semantic HTML like `label`, `ul`, `li` for better accessibility and readability.
* **CSS for Basic Styling:**  Includes basic CSS to improve the visual appearance and layout.  Crucially, it uses classes to style based on priority, making the visual feedback more useful.  The CSS uses `flexbox` for better layout of list items.
* **JavaScript for Task Management:**
    * **`tasks` Array:**  This array holds the task objects.
    * **`nextTaskId`:**  A simple ID generator to ensure unique IDs for each task.
    * **`addTask()` function:**
        * Gets values from the input fields.
        * Includes input validation to ensure the task name is not empty.
        * Creates a `task` object.
        * Adds the `task` to the `tasks` array.
        * Calls `renderTaskList()` to update the UI.
        * Clears the form after adding the task.
    * **`renderTaskList()` function:**
        * Clears the existing task list in the HTML.
        * Iterates through the `tasks` array.
        * For each `task`, creates an `li` element and populates it with the task name and buttons (Complete, Delete, Details).
        * Adds the appropriate priority class (`priority-low`, `priority-medium`, `priority-high`) to the list item.  This is essential for the "Smart" aspect.
        * Appends the `li` element to the `ul` element.
    * **`completeTask()` function:**
        * Finds the task in the `tasks` array using its ID.
        * Toggles the `completed` property of the task.
        * Re-renders the task list to update the button text.
    * **`deleteTask()` function:**
        * Filters the `tasks` array to create a *new* array that excludes the task to be deleted.  This is important for immutability and avoids unexpected side effects.
        * Re-renders the task list.
    * **`showTaskDetails()` and `hideTaskDetails()` functions:**  Implement the displaying and hiding of task details.  The details are shown in a separate `div` element.
* **Priority Levels:**  The `priority` property and the CSS classes `priority-low`, `priority-medium`, and `priority-high` are used to visually represent the task priority.
* **Clearer Code:** The code is now more readable and maintainable with better variable names and comments.
* **Error Handling:** Basic error handling (checking for empty task name) is included.
* **Complete/Undo Functionality:** The "Complete" button toggles the completion status of the task and changes its text to "Undo".
* **Details Functionality:** The Details button shows a description and priority.
* **No API Interaction (Simplified):**  This version focuses on the client-side logic.  To integrate with an API, you would add `fetch` calls to:
    * `addTask()`:  POST the new task data to the API endpoint.
    * On page load: GET the initial task data from the API endpoint and populate the `tasks` array.
    * `completeTask()`:  PUT or PATCH the updated task data to the API endpoint.
    * `deleteTask()`:  DELETE the task from the API endpoint.
* **Id management:** Uses a simple `nextTaskId` to create unique IDs. While suitable for a client-side example, a proper backend should handle ID generation.
* **Input trimming:** Calls `trim()` on the input values to remove leading and trailing spaces.

How to Run:

1.  **Save:** Save the code above as an HTML file (e.g., `task_manager.html`).
2.  **Open in Browser:** Open the `task_manager.html` file in your web browser.
3.  **Interact:**  You can now add, complete, delete, and view details of tasks.

To make this a *true* web-based application, you would need a backend API to store and retrieve the task data persistently (e.g., using Node.js, Python/Flask, Java/Spring Boot).  The JavaScript code would then make API calls (using `fetch`) to interact with the backend.
👁️ Viewed: 10

Comments