function addTask(status) {
const column = document.getElementById(status);
code
// Hide the "Add a card" button
const addCardButton = column.querySelector('.add-card');
addCardButton.style.display = 'none';
// Create a new task card div
const newCard = document.createElement('div');
newCard.classList.add('task-card');
newCard.contentEditable = 'true'; // Make the new card editable
// Add event listener to handle saving when 'Enter' is pressed
newCard.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault(); // Prevent new lines when pressing Enter
const taskTitle = newCard.textContent.trim();
if (taskTitle) {
// Send task title and status to the backend
axios.post('/api/tasks', { title: taskTitle, status })
.then(() => {
loadTasks(); // Reload tasks after adding new one
addCardButton.style.display = 'block'; // Show "Add a card" button again
});
} else {
// Remove the card if no text was entered
newCard.remove();
addCardButton.style.display = 'block'; // Show "Add a card" button again
}
}
});
// Add event listener for "Escape" key to discard the card
newCard.addEventListener('keydown', function(event) {
if (event.key === 'Escape') {
newCard.remove(); // Discard the new card
addCardButton.style.display = 'block'; // Show "Add a card" button again
}
});
// Append the new card to the column
column.appendChild(newCard);
// Focus on the new card to allow typing immediately
newCard.focus();
function updateTaskTitle(taskId, element) {
const newTitle = element.textContent.trim();
axios.put(/api/tasks/${taskId}, { title: newTitle })
.then((response) => {
if (response.data.deleted) {
// If the task was deleted (empty title), remove it from the UI
element.closest('.task-card').remove();
} else {
// If the task was updated, reload tasks to reflect any changes
loadTasks();
}
})
.catch((error) => {
console.error('Error updating task:', error);
loadTasks(); // Reload tasks to ensure UI is in sync with server
});
}
function addHabit() {
const name = document.getElementById('new-habit').value;
const days = []; // You might want to add a way for users to select days
if (name) {
axios.post('/api/habits', { name, days })
.then(() => {
document.getElementById('new-habit').value = '';
loadHabits();
});
}
}
// Load tasks and habits on page load
loadTasks();
loadHabits();
I'm thinking I could do something better with my html or javascript so that I can easily reorder tasks while still keeping all my other features, including editing after creating tasks and adding new tasks. Does my html or js need a structural overhaul so that I don't need to call my app.py (attached below again) to reorder tasks?
app.py
from flask import Flask, request, jsonify, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from datetime import date
import os
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from apscheduler.schedulers.background import BackgroundScheduler
import logging
import requests
def archive_tasks():
with app.app_context():
# Check last archive date
last_archived_date = ArchiveInfo.get_last_archive()
today = date.today()
code
# If the last archive was not today, archive and update the record
if last_archived_date is None or last_archived_date != today:
# Perform the archive
tasks = Task.query.filter(Task.status == 'finished')
for task in tasks:
task.status = 'archived'
db.session.commit()
# Update the archive info in the database
ArchiveInfo.update_last_archive(today)
logging.info(f"Archived tasks for {today}")
class ArchiveInfo(db.Model):
id = db.Column(db.Integer, primary_key=True)
last_archive = db.Column(db.Date, nullable=False)
code
@staticmethod
def get_last_archive():
archive_info = ArchiveInfo.query.first()
if archive_info:
return archive_info.last_archive
return None
@staticmethod
def update_last_archive(new_archive_date):
archive_info = ArchiveInfo.query.first()
if not archive_info:
archive_info = ArchiveInfo(last_archive=new_archive_date)
db.session.add(archive_info)
else:
archive_info.last_archive = new_archive_date
db.session.commit()
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
status = db.Column(db.String(20), nullable=False)
completion_date = db.Column(db.Date)
column = db.Column(db.String(20), default='To Do')
def to_dict(self):
return {
'id': self.id,
'title': self.title,
'status': self.status,
'completion_date': self.completion_date.isoformat() if self.completion_date else None,
'column': self.column
}
class Habit(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
#days that the habit is available
days = db.Column(db.String(100)) # Store as comma-separated string
#list of completed dates
dates = db.relationship('HabitDate', backref='habit', lazy=True)
class HabitDate(db.Model):
id = db.Column(db.Integer, primary_key=True)
habit_id = db.Column(db.Integer, db.ForeignKey('habit.id'), nullable=False)
date = db.Column(db.Date, nullable=False)
class JournalEntry(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
date = db.Column(db.Date, nullable=False)
ai_comment = db.Column(db.Text)
@app.route('/api/tasks', methods=['GET', 'POST'])
def handle_tasks():
'''
POST request: Creates a new task in the database and returns its details.
GET request: Retrieves and returns all tasks from the database as a list in JSON format.
'''
if request.method == 'POST':
data = request.json
new_task = Task(
title=data['title'],
status=data['status'],
column=data.get('column', 'To Do')
)
db.session.add(new_task)
db.session.commit()
return jsonify(id=new_task.id, title=new_task.title, status=new_task.status, column=new_task.column)
else:
tasks = Task.query.all()
return jsonify([{
'id': task.id,
'title': task.title,
'status': task.status,
'completion_date': str(task.completion_date) if task.completion_date else None,
'column': task.column
} for task in tasks])
@app.route('/api/tasks/int:task_id', methods=['PUT', 'DELETE'])
def update_task(task_id):
task = Task.query.get_or_404(task_id)
if request.method == 'PUT':
data = request.json
if 'title' in data and not data['title'].strip():
# If the title is empty, delete the task
db.session.delete(task)
db.session.commit()
return jsonify({'success': True, 'deleted': True})
else:
task.title = data.get('title', task.title)
task.status = data.get('status', task.status)
task.column = data.get('column', task.column)
if data.get('status') == 'finished':
task.completion_date = date.today()
else:
task.completion_date = None
db.session.commit()
return jsonify({'success': True, 'deleted': False})
elif request.method == 'DELETE':
db.session.delete(task)
db.session.commit()
return jsonify({'success': True})
@app.route('/api/tasks/archive', methods=["POST"])
def archive_completed_tasks():
tasks = Task.query.filter(Task.status == 'finished')
for task in tasks:
task.status = 'archived'
db.session.commit()
return jsonify({'success': True})
@app.route('/api/habits', methods=['GET', 'POST'])
def handle_habits():
'''
POST request: Creates a new habit in db and returns related JSON
GET request: Returns a JSON of all habits and related fields
'''
if request.method == 'POST':
data = request.json
new_habit = Habit(name=data['name'], days=','.join(data.get('days', [])))
db.session.add(new_habit)
db.session.commit()
return jsonify(id=new_habit.id, name=new_habit.name, days=new_habit.days.split(','))
else:
habits = Habit.query.all()
return jsonify([{
'id': habit.id,
'name': habit.name,
'days': habit.days.split(',') if habit.days else []
} for habit in habits])
if not task_id or new_order is None:
return jsonify({'success': False, 'error': 'Missing taskId or newOrder'}), 400
try:
task = Task.query.get(task_id)
if task:
if new_status and new_status != task.status:
# If the status has changed, move the task to the end of the new status
max_order = db.session.query(db.func.max(Task.order)).filter(Task.status == new_status).scalar() or 0
task.order = max_order + 1
task.status = new_status
else:
# Otherwise, just update the order
task.order = new_order
db.session.commit()
return jsonify({'success': True})
except Exception as e:
db.session.rollback()
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/habits/int:habit_id', methods=['PUT', 'DELETE'])
def update_habit(habit_id):
'''
PUT request: Change Habit name and days
DELETE request: Delete the habit
'''
try:
habit = Habit.query.get_or_404(habit_id)
if request.method == 'PUT':
data = request.json
if 'name' in data:
habit.name = data['name']
if 'days' in data:
habit.days = ','.join(map(str, data['days']))
if 'toggle_date' in data:
toggle_date = date.fromisoformat(data['toggle_date'])
existing_date = HabitDate.query.filter_by(habit_id=habit.id, date=toggle_date).first()
if existing_date:
db.session.delete(existing_date)
else:
new_date = HabitDate(habit_id=habit.id, date=toggle_date)
db.session.add(new_date)
db.session.commit()
return jsonify({'success': True})
elif request.method == 'DELETE':
db.session.delete(habit)
db.session.commit()
return jsonify({'success': True})
except Exception as e:
app.logger.error(f"An error occurred while updating habit {habit_id}: {str(e)}")
return jsonify({'success': False, 'error': str(e)}), 500
yearly_data = {}
for habit in habits:
habit_dates = HabitDate.query.filter_by(habit_id=habit.id).all()
for habit_date in habit_dates:
date_str = str(habit_date.date)
if date_str not in yearly_data:
yearly_data[date_str] = {"completedHabits": [], "completedTasks": [], "journalEntries": []}
yearly_data[date_str]["completedHabits"].append(habit.name)
for task in tasks:
date_str = str(task.completion_date)
if date_str not in yearly_data:
yearly_data[date_str] = {"completedHabits": [], "completedTasks": [], "journalEntries": []}
yearly_data[date_str]["completedTasks"].append(task.title)
for entry in journal_entries:
date_str = str(entry.date)
if date_str not in yearly_data:
yearly_data[date_str] = {"completedHabits": [], "completedTasks": [], "journalEntries": []}
yearly_data[date_str]["journalEntries"].append(entry.title)
for date_str, data in yearly_data.items():
total_habits = len(habits)
completed_habits = len(data["completedHabits"])
data["completionRate"] = completed_habits / total_habits if total_habits > 0 else 0
# Return the data with date strings as keys
return jsonify(yearly_data)
if name == 'main':
with app.app_context():
db.create_all()
app.run(debug=True)
To answer your question: Yes, to avoid calling your app.py (Flask backend) when reordering tasks, you'll need to make some adjustments to your JavaScript code, but a complete structural overhaul may not be necessary.
Here's why:
Understanding the Requirement
Persisting Order vs. Client-Side Reordering: If you want the new order of tasks to persist across page reloads and sessions (like Trello does), you need to save the new order to the backend database. This inherently requires API calls to your Flask app.
Client-Side Only Reordering: If you're okay with the new order being temporary (i.e., it resets when the page reloads), you can manage the reordering entirely on the client side without any API calls.
Recommendations
Option 1: Client-Side Reordering Without Backend Calls
If you decide that persisting the task order isn't necessary, you can adjust your JavaScript code to handle reordering purely on the front end.
Simplify Drag-and-Drop Logic: Your current drag-and-drop handlers (handleDragStart, handleDragOver, handleDrop, handleDragEnd) manage the DOM elements directly. You can remove the updateTaskOrder function and any API calls related to reordering.
Adjust handleDrop Function: Modify the handleDrop function to reorder the DOM elements without making any backend calls.
Remove Backend Order Updates: Since you're not persisting the order, you can remove any code that makes API calls to update the task order.
Option 2: Persisting Order by Optimizing Backend Calls
If persisting the task order is important, you still need to communicate with your backend. However, you can optimize your code to minimize the number of API calls and make your code cleaner.
Use Libraries for Drag-and-Drop: Consider using a well-tested library like SortableJS or Dragula. These libraries simplify drag-and-drop functionality and handle many edge cases.
SortableJS Example:
html
<!-- Include SortableJS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.14.0/Sortable.min.js" integrity="sha512-CrLRuBu2kr6bbGRYiPZ2PB+zyXo4v+X8+AyX1fks45/6HK3YObxYhKBS59PSxdpoahxMemxK3hV1KZnF1FXJBQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
javascript
// Initialize Sortable on each column
columnOrder.forEach(status => {
const column = document.getElementById(status);
Sortable.create(column, {
group: 'tasks',
animation: 150,
onEnd: function (/**Event*/evt) {
const itemEl = evt.item; // dragged item
const fromStatus = evt.from.id;
const toStatus = evt.to.id;
const tasks = Array.from(evt.to.children)
.filter(child => child.classList.contains('task-card'))
.map((task, index) => ({
id: task.dataset.taskId,
order: index
}));
// Send updated order and status to backend
axios.put('/api/tasks/order', {
tasks: tasks,
status: toStatus
}).then(() => {
loadTasks();
});
},
});
});
Conclusion
If Persisting Order Is Not Essential: You can avoid backend calls by handling reordering entirely in the frontend. This requires minor adjustments to your JavaScript code.
If You Need to Persist Order: You'll need to keep the interaction with your backend but optimize your code. Using a library like SortableJS simplifies your drag-and-drop logic and makes it easier to manage task orders efficiently. It'll batch the order updates, and your backend can process them in one call.
Additional Suggestions
Simplify Your JavaScript Code: Libraries abstract away the complexities of drag-and-drop interactions. They handle edge cases and provide a smoother user experience.
Consistency in Code: Ensure that your front-end and back-end code are in sync. In your code, you had a comment mentioning that /api/tasks/order doesn't exist, but you have it in your app.py. Double-check your routes and API endpoints.
Error Handling: Enhance error handling in your JavaScript code to provide feedback to users if something goes wrong during reordering.
Avoid Redundant Calls: Only reload tasks (loadTasks()) when necessary. If you already have the updated data, you can manipulate the DOM accordingly without fetching all tasks again.
Final Thoughts
You don't necessarily need a complete structural overhaul of your HTML or JavaScript. By integrating a drag-and-drop library and adjusting how you handle task ordering updates, you can achieve the desired functionality more efficiently.
Remember, the key is to balance user experience with technical considerations:
For Optimal UX with Persisted Data: Use backend calls to save the order, but optimize your code to handle it effectively.
For Simplified Implementation: If immediate persistence isn't crucial, handle everything on the client side.
Choose the approach that best fits your application's needs and your users' expectations.
Not yet included in a published release.
Optimize Backend Endpoint: Modify your /api/tasks/order endpoint to accept an array of tasks with their new orders and statuses.
python
@app.route('/api/tasks/order', methods=['PUT'])
def update_task_order():
data = request.json
tasks = data.get('tasks', [])
status = data.get('status')
try:
for task_data in tasks:
task = Task.query.get(task_data['id'])
if task:
task.order = task_data['order']
task.status = status
db.session.commit()
return jsonify({'success': True})
except Exception as e:
db.session.rollback()
return jsonify({'success': False, 'error': str(e)}), 500
Ensure your Task model has an order field:
python
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
status = db.Column(db.String(20), nullable=False)
completion_date = db.Column(db.Date)
column = db.Column(db.String(20), default='To Do')
order = db.Column(db.Integer, nullable=False, default=0)
def to_dict(self):
return {
'id': self.id,
'title': self.title,
'status': self.status,
'completion_date': self.completion_date.isoformat() if self.completion_date else None,
'column': self.column,
'order': self.order
}
Load Tasks in Order: Update your loadTasks function to display tasks based on their order.
javascript
function loadTasks() {
axios.get('/api/tasks')
.then(response => {
const tasks = response.data;
// Sort tasks by order
tasks.sort((a, b) => a.order - b.order);
// Rest of your code...
});
}