Farben der Habits wälbarmachen

This commit is contained in:
jafreli
2025-07-16 22:57:28 +02:00
parent 04c40b29d9
commit 8580a82222
5 changed files with 146 additions and 32 deletions

23
app.py
View File

@@ -32,7 +32,8 @@ def get_habits():
current_habit_data = { current_habit_data = {
'id': habit_doc.doc_id, 'id': habit_doc.doc_id,
'name': habit_doc.get('name'), 'name': habit_doc.get('name'),
'completed_dates': habit_doc.get('completed_dates', []) 'completed_dates': habit_doc.get('completed_dates', []),
'color': habit_doc.get('color', '#4CAF50')
} }
completion_history = {} completion_history = {}
@@ -48,11 +49,12 @@ def get_habits():
def add_habit(): def add_habit():
data = request.json data = request.json
name = data.get('name') name = data.get('name')
color = data.get('color', '#4CAF50') # Default green color
if not name: if not name:
return jsonify({'error': 'Habit name is required'}), 400 return jsonify({'error': 'Habit name is required'}), 400
habit_id = db.insert({'name': name, 'completed_dates': []}) habit_id = db.insert({'name': name, 'completed_dates': [], 'color': color})
return jsonify({'id': habit_id, 'name': name, 'completed_dates': []}), 201 return jsonify({'id': habit_id, 'name': name, 'completed_dates': [], 'color': color}), 201
@app.route('/habits/<int:habit_id>/complete', methods=['POST']) @app.route('/habits/<int:habit_id>/complete', methods=['POST'])
def complete_habit(habit_id): def complete_habit(habit_id):
@@ -86,16 +88,23 @@ def uncomplete_habit(habit_id):
def update_habit(habit_id): def update_habit(habit_id):
data = request.json data = request.json
name = data.get('name') name = data.get('name')
color = data.get('color')
if not name: if not name and not color:
return jsonify({'error': 'Habit name is required'}), 400 return jsonify({'error': 'Habit name or color is required'}), 400
habit = db.get(doc_id=habit_id) habit = db.get(doc_id=habit_id)
if not habit: if not habit:
return jsonify({'error': 'Habit not found'}), 404 return jsonify({'error': 'Habit not found'}), 404
db.update({'name': name}, doc_ids=[habit_id]) update_data = {}
return jsonify({'message': f'Habit {habit_id} updated', 'name': name}) if name:
update_data['name'] = name
if color:
update_data['color'] = color
db.update(update_data, doc_ids=[habit_id])
return jsonify({'message': f'Habit {habit_id} updated', **update_data})
@app.route('/habits/<int:habit_id>', methods=['DELETE']) @app.route('/habits/<int:habit_id>', methods=['DELETE'])
def delete_habit(habit_id): def delete_habit(habit_id):

View File

@@ -1 +1 @@
{"_default": {"1": {"name": "Zocken Mega", "completed_dates": ["2025-07-16", "2025-07-14", "2025-08-01", "2025-08-09", "2025-08-17", "2025-07-15", "2025-07-01", "2025-06-29", "2025-06-19", "2025-06-20", "2025-07-13", "2025-07-12"]}, "2": {"name": "Laufen", "completed_dates": []}}} {"_default": {"1": {"name": "Zocken Mega", "completed_dates": ["2025-07-14", "2025-08-01", "2025-08-09", "2025-08-17", "2025-07-15", "2025-07-01", "2025-06-29", "2025-06-19", "2025-06-20", "2025-07-13", "2025-07-12", "2025-07-16"], "color": "#08680c"}, "2": {"name": "Laufen", "completed_dates": ["2025-07-16", "2025-07-02"], "color": "#1a3ed1"}}}

View File

@@ -89,7 +89,7 @@ h1 {
} }
.habit-actions button.completed-today { .habit-actions button.completed-today {
color: #4CAF50; color: var(--habit-color, #4CAF50);
} }
.habit-actions button.not-completed-today { .habit-actions button.not-completed-today {
@@ -97,11 +97,12 @@ h1 {
} }
.habit-actions button.completed-today:hover { .habit-actions button.completed-today:hover {
color: #45a049; color: var(--habit-color, #45a049);
filter: brightness(0.9);
} }
.habit-actions button.not-completed-today:hover { .habit-actions button.not-completed-today:hover {
color: #4CAF50; color: var(--habit-color, #4CAF50);
} }
.date-grid { .date-grid {
@@ -133,7 +134,7 @@ h1 {
} }
.date-square.completed { .date-square.completed {
background-color: #4CAF50; background-color: var(--habit-color, #4CAF50);
} }
/* Modal Styles */ /* Modal Styles */
@@ -188,7 +189,7 @@ h1 {
#modalHabitName { #modalHabitName {
text-align: center; text-align: center;
color: #4CAF50; color: var(--current-habit-color, #4CAF50);
margin-bottom: 20px; margin-bottom: 20px;
} }
@@ -200,8 +201,8 @@ h1 {
} }
.month-navigation button { .month-navigation button {
background-color: #4CAF50; background-color: var(--current-habit-color, #4CAF50);
color: white; color: var(--current-habit-text-color, white);
border: none; border: none;
border-radius: 5px; border-radius: 5px;
padding: 8px 12px; padding: 8px 12px;
@@ -210,7 +211,9 @@ h1 {
} }
.month-navigation button:hover { .month-navigation button:hover {
background-color: #45a049; background-color: var(--current-habit-color, #45a049);
color: var(--current-habit-text-color, white);
filter: brightness(0.9);
} }
#currentMonthYear { #currentMonthYear {
@@ -226,7 +229,7 @@ h1 {
margin-bottom: 10px; margin-bottom: 10px;
text-align: center; text-align: center;
font-weight: bold; font-weight: bold;
color: #4CAF50; color: var(--current-habit-color, #4CAF50);
} }
.weekdays-header div { .weekdays-header div {
@@ -251,7 +254,8 @@ h1 {
} }
.date-cell.completed { .date-cell.completed {
background-color: #4CAF50; background-color: var(--current-habit-color, #4CAF50);
color: var(--current-habit-text-color, white);
} }
.date-cell.today { .date-cell.today {
@@ -304,12 +308,14 @@ h1 {
} }
#modalCompleteTodayBtn { #modalCompleteTodayBtn {
background-color: #4CAF50; background-color: var(--current-habit-color, #4CAF50);
color: white; color: var(--current-habit-text-color, white);
} }
#modalCompleteTodayBtn:hover { #modalCompleteTodayBtn:hover {
background-color: #45a049; background-color: var(--current-habit-color, #45a049);
color: var(--current-habit-text-color, white);
filter: brightness(0.9);
} }
#modalEditBtn { #modalEditBtn {
@@ -328,4 +334,26 @@ h1 {
#modalDeleteBtn:hover { #modalDeleteBtn:hover {
background-color: #c82333; background-color: #c82333;
}
.color-picker-section {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 20px;
gap: 10px;
}
.color-picker-section label {
color: #e0e0e0;
font-weight: bold;
}
#habitColorPicker {
width: 40px;
height: 40px;
border: none;
border-radius: 50%;
cursor: pointer;
background: none;
} }

View File

@@ -12,6 +12,7 @@ const modalDeleteBtn = document.getElementById('modalDeleteBtn'); // Neu hinzuge
let currentHabitId = null; // Stellt sicher, dass diese globale Variable korrekt ist let currentHabitId = null; // Stellt sicher, dass diese globale Variable korrekt ist
let currentModalDate = new Date(); // Aktueller Monat im Modal let currentModalDate = new Date(); // Aktueller Monat im Modal
let currentHabitCompletedDates = []; // Completed dates für das aktuelle Habit let currentHabitCompletedDates = []; // Completed dates für das aktuelle Habit
let currentHabitColor = '#4CAF50'; // Current habit color
function getCurrentDate() { function getCurrentDate() {
const today = new Date(); const today = new Date();
@@ -38,23 +39,23 @@ function calculateStreak(completedDates) {
if (!completedDates || completedDates.length === 0) { if (!completedDates || completedDates.length === 0) {
return 0; return 0;
} }
// Sort dates in descending order (newest first) // Sort dates in descending order (newest first)
const sortedDates = completedDates.sort((a, b) => new Date(b) - new Date(a)); const sortedDates = completedDates.sort((a, b) => new Date(b) - new Date(a));
const today = getCurrentDate(); const today = getCurrentDate();
let streak = 0; let streak = 0;
let currentDate = new Date(); let currentDate = new Date();
// Check if today is completed, if not, start from yesterday // Check if today is completed, if not, start from yesterday
if (!sortedDates.includes(today)) { if (!sortedDates.includes(today)) {
currentDate.setDate(currentDate.getDate() - 1); currentDate.setDate(currentDate.getDate() - 1);
} }
// Count consecutive days backwards from today (or yesterday) // Count consecutive days backwards from today (or yesterday)
while (true) { while (true) {
const dateStr = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, '0')}-${String(currentDate.getDate()).padStart(2, '0')}`; const dateStr = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, '0')}-${String(currentDate.getDate()).padStart(2, '0')}`;
if (sortedDates.includes(dateStr)) { if (sortedDates.includes(dateStr)) {
streak++; streak++;
currentDate.setDate(currentDate.getDate() - 1); currentDate.setDate(currentDate.getDate() - 1);
@@ -62,7 +63,7 @@ function calculateStreak(completedDates) {
break; break;
} }
} }
return streak; return streak;
} }
@@ -85,6 +86,10 @@ function renderHabits(habits) {
habitItem.className = 'habit-item'; habitItem.className = 'habit-item';
habitItem.dataset.id = habit.id; // Store habit ID habitItem.dataset.id = habit.id; // Store habit ID
// Apply custom color to the habit item
const habitColor = habit.color || '#4CAF50';
habitItem.style.setProperty('--habit-color', habitColor);
const habitHeader = document.createElement('div'); const habitHeader = document.createElement('div');
habitHeader.className = 'habit-header'; habitHeader.className = 'habit-header';
@@ -108,7 +113,7 @@ function renderHabits(habits) {
// Drei-Punkte-Menü für erweiterte Optionen // Drei-Punkte-Menü für erweiterte Optionen
const menuButton = document.createElement('button'); const menuButton = document.createElement('button');
menuButton.innerHTML = '&#x22EE;'; // Vertical ellipsis (drei Punkte) menuButton.innerHTML = '&#x22EE;'; // Vertical ellipsis (drei Punkte)
menuButton.onclick = () => openHabitModal(habit.id, habit.name, habit.completed_dates); menuButton.onclick = () => openHabitModal(habit.id, habit.name, habit.completed_dates, habitColor);
habitActions.appendChild(menuButton); habitActions.appendChild(menuButton);
habitHeader.appendChild(habitActions); habitHeader.appendChild(habitActions);
habitItem.appendChild(habitHeader); habitItem.appendChild(habitHeader);
@@ -130,16 +135,16 @@ function renderHabits(habits) {
// Streak Counter hinzufügen // Streak Counter hinzufügen
const streakContainer = document.createElement('div'); const streakContainer = document.createElement('div');
streakContainer.className = 'streak-container'; streakContainer.className = 'streak-container';
const flameIcon = document.createElement('span'); const flameIcon = document.createElement('span');
flameIcon.className = 'flame-icon'; flameIcon.className = 'flame-icon';
flameIcon.innerHTML = '🔥'; // Flammen-Emoji flameIcon.innerHTML = '🔥'; // Flammen-Emoji
const streakCount = document.createElement('span'); const streakCount = document.createElement('span');
streakCount.className = 'streak-count'; streakCount.className = 'streak-count';
const currentStreak = calculateStreak(habit.completed_dates); const currentStreak = calculateStreak(habit.completed_dates);
streakCount.textContent = `${currentStreak} Tag${currentStreak !== 1 ? 'e' : ''}`; streakCount.textContent = `${currentStreak} Tag${currentStreak !== 1 ? 'e' : ''}`;
streakContainer.appendChild(flameIcon); streakContainer.appendChild(flameIcon);
streakContainer.appendChild(streakCount); streakContainer.appendChild(streakCount);
habitItem.appendChild(streakContainer); habitItem.appendChild(streakContainer);
@@ -172,9 +177,10 @@ async function addHabit() {
} }
} }
async function openHabitModal(habitId, habitName, completedDates) { async function openHabitModal(habitId, habitName, completedDates, habitColor = '#4CAF50') {
currentHabitId = habitId; currentHabitId = habitId;
currentHabitCompletedDates = completedDates; currentHabitCompletedDates = completedDates;
currentHabitColor = habitColor;
currentModalDate = new Date(); // Reset to current month currentModalDate = new Date(); // Reset to current month
modalHabitName.textContent = habitName; modalHabitName.textContent = habitName;
@@ -183,6 +189,16 @@ async function openHabitModal(habitId, habitName, completedDates) {
modalEditBtn.dataset.habitId = habitId; modalEditBtn.dataset.habitId = habitId;
modalDeleteBtn.dataset.habitId = habitId; modalDeleteBtn.dataset.habitId = habitId;
// Set color picker to current habit color
document.getElementById('habitColorPicker').value = habitColor;
// Set CSS variable for modal elements
dateModal.style.setProperty('--current-habit-color', habitColor);
// Set contrast color for text on colored backgrounds
const contrastColor = getContrastColor(habitColor);
dateModal.style.setProperty('--current-habit-text-color', contrastColor);
renderModalCalendar(); renderModalCalendar();
dateModal.style.display = 'flex'; dateModal.style.display = 'flex';
} }
@@ -404,4 +420,61 @@ async function toggleTodayCompletion(habitId, date, buttonElement) {
} catch (error) { } catch (error) {
console.error('Error toggling habit completion:', error); console.error('Error toggling habit completion:', error);
} }
}
async function updateHabitColor() {
if (!currentHabitId) {
console.error('No habit selected for color update.');
return;
}
const newColor = document.getElementById('habitColorPicker').value;
currentHabitColor = newColor;
try {
const response = await fetch(`/habits/${currentHabitId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ color: newColor })
});
const data = await response.json();
if (response.ok) {
// Update CSS variable for modal elements
dateModal.style.setProperty('--current-habit-color', newColor);
// Update contrast color for text on colored backgrounds
const contrastColor = getContrastColor(newColor);
dateModal.style.setProperty('--current-habit-text-color', contrastColor);
// Update modal calendar colors immediately
updateModalColors(newColor);
// Refresh habits list to show new color
fetchHabits();
} else {
console.error('Failed to update habit color:', data.error);
}
} catch (error) {
console.error('Error updating habit color:', error);
}
}
function updateModalColors(color) {
// Update completed date cells in modal
const completedCells = modalDateGrid.querySelectorAll('.date-cell.completed');
completedCells.forEach(cell => {
cell.style.backgroundColor = color;
});
}
function getContrastColor(hexColor) {
// Convert hex to RGB
const r = parseInt(hexColor.slice(1, 3), 16);
const g = parseInt(hexColor.slice(3, 5), 16);
const b = parseInt(hexColor.slice(5, 7), 16);
// Calculate luminance
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
// Return dark text for light colors, light text for dark colors
return luminance > 0.5 ? '#333333' : '#ffffff';
} }

View File

@@ -36,6 +36,10 @@
<div>So</div> <div>So</div>
</div> </div>
<div id="modalDateGrid" class="date-grid-modal"></div> <div id="modalDateGrid" class="date-grid-modal"></div>
<div class="color-picker-section">
<label for="habitColorPicker">Farbe wählen:</label>
<input type="color" id="habitColorPicker" onchange="updateHabitColor()">
</div>
<div class="modal-actions"> <div class="modal-actions">
<button id="modalCompleteTodayBtn" onclick="completeHabitForDate(event, currentHabitId, getCurrentDate())">Heute erledigen</button> <button id="modalCompleteTodayBtn" onclick="completeHabitForDate(event, currentHabitId, getCurrentDate())">Heute erledigen</button>
<button id="modalEditBtn" onclick="editHabitName()">Bearbeiten</button> <button id="modalEditBtn" onclick="editHabitName()">Bearbeiten</button>