Mehrere an einem Tag

This commit is contained in:
jafreli
2025-07-18 23:16:44 +02:00
parent 866e6c95b7
commit 93f6026346
5 changed files with 337 additions and 84 deletions

View File

@@ -11,8 +11,9 @@ const modalDeleteBtn = document.getElementById('modalDeleteBtn'); // Neu hinzuge
let currentHabitId = null; // Stellt sicher, dass diese globale Variable korrekt ist
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 (now object with counts)
let currentHabitColor = '#4CAF50'; // Current habit color
let currentHabitDailyTarget = 1; // Current habit daily target
function getCurrentDate() {
const today = new Date();
@@ -35,28 +36,27 @@ function getPastDates(days) {
return dates;
}
function calculateStreak(completedDates) {
if (!completedDates || completedDates.length === 0) {
function calculateStreak(completedDates, dailyTarget) {
if (!completedDates || Object.keys(completedDates).length === 0) {
return 0;
}
// Sort dates in descending order (newest first)
const sortedDates = completedDates.sort((a, b) => new Date(b) - new Date(a));
const today = getCurrentDate();
let streak = 0;
let currentDate = new Date();
// Check if today is completed, if not, start from yesterday
if (!sortedDates.includes(today)) {
const todayCount = completedDates[today] || 0;
if (todayCount < dailyTarget) {
currentDate.setDate(currentDate.getDate() - 1);
}
// Count consecutive days backwards from today (or yesterday)
while (true) {
const dateStr = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, '0')}-${String(currentDate.getDate()).padStart(2, '0')}`;
const count = completedDates[dateStr] || 0;
if (sortedDates.includes(dateStr)) {
if (count >= dailyTarget) {
streak++;
currentDate.setDate(currentDate.getDate() - 1);
} else {
@@ -101,19 +101,28 @@ function renderHabits(habits) {
const habitActions = document.createElement('div');
habitActions.className = 'habit-actions';
// Haken-Button für heute abhaken/rückgängig machen
// Haken-Button für heute abhaken/rückgängig machen mit Zähler
const todayToggleButton = document.createElement('button');
const today = getCurrentDate();
const isCompletedToday = habit.completed_dates && habit.completed_dates.includes(today);
todayToggleButton.innerHTML = isCompletedToday ? '&#x2713;' : '&#x2713;'; // Checkmark symbol
const todayCount = habit.completed_dates[today] || 0;
const dailyTarget = habit.daily_target || 1;
const isCompletedToday = todayCount >= dailyTarget;
// Show count if target > 1, otherwise just checkmark
if (dailyTarget > 1) {
todayToggleButton.innerHTML = `${todayCount}/${dailyTarget}`;
} else {
todayToggleButton.innerHTML = '&#x2713;'; // Checkmark symbol
}
todayToggleButton.className = isCompletedToday ? 'completed-today' : 'not-completed-today';
todayToggleButton.onclick = () => toggleTodayCompletion(habit.id, today, todayToggleButton);
todayToggleButton.onclick = () => toggleTodayCompletion(habit.id, today, todayToggleButton, habit.daily_target);
habitActions.appendChild(todayToggleButton);
// Drei-Punkte-Menü für erweiterte Optionen
const menuButton = document.createElement('button');
menuButton.innerHTML = '&#x22EE;'; // Vertical ellipsis (drei Punkte)
menuButton.onclick = () => openHabitModal(habit.id, habit.name, habit.completed_dates, habitColor);
menuButton.onclick = () => openHabitModal(habit.id, habit.name, habit.completed_dates, habitColor, habit.daily_target);
habitActions.appendChild(menuButton);
habitHeader.appendChild(habitActions);
habitItem.appendChild(habitHeader);
@@ -124,10 +133,18 @@ function renderHabits(habits) {
last30Days.forEach(date => {
const dateSquare = document.createElement('div');
dateSquare.className = 'date-square';
if (habit.completed_dates && habit.completed_dates.includes(date)) {
dateSquare.classList.add('completed');
const dateCount = habit.completed_dates[date] || 0;
const isCompleted = dateCount >= dailyTarget;
// Apply gradient styling based on completion percentage
applyCompletionStyling(dateSquare, dateCount, dailyTarget, habitColor);
// Show count in tooltip if target > 1
if (dailyTarget > 1) {
dateSquare.title = `${date}: ${dateCount}/${dailyTarget}`;
} else {
dateSquare.title = date;
}
dateSquare.title = date; // Show date on hover
dateGrid.appendChild(dateSquare);
});
habitItem.appendChild(dateGrid);
@@ -142,7 +159,7 @@ function renderHabits(habits) {
const streakCount = document.createElement('span');
streakCount.className = 'streak-count';
const currentStreak = calculateStreak(habit.completed_dates);
const currentStreak = calculateStreak(habit.completed_dates, dailyTarget);
streakCount.textContent = `${currentStreak} Tag${currentStreak !== 1 ? 'e' : ''}`;
streakContainer.appendChild(flameIcon);
@@ -177,10 +194,11 @@ async function addHabit() {
}
}
async function openHabitModal(habitId, habitName, completedDates, habitColor = '#4CAF50') {
async function openHabitModal(habitId, habitName, completedDates, habitColor = '#4CAF50', dailyTarget = 1) {
currentHabitId = habitId;
currentHabitCompletedDates = completedDates;
currentHabitColor = habitColor;
currentHabitDailyTarget = dailyTarget;
currentModalDate = new Date(); // Reset to current month
modalHabitName.textContent = habitName;
@@ -192,6 +210,9 @@ async function openHabitModal(habitId, habitName, completedDates, habitColor = '
// Set color picker to current habit color
document.getElementById('habitColorPicker').value = habitColor;
// Set daily target input to current value
document.getElementById('habitDailyTarget').value = dailyTarget;
// Set CSS variable for modal elements
dateModal.style.setProperty('--current-habit-color', habitColor);
@@ -236,9 +257,15 @@ function renderModalCalendar() {
dateCell.className = 'date-cell';
dateCell.textContent = day;
if (currentHabitCompletedDates.includes(dateStr)) {
const dateCount = currentHabitCompletedDates[dateStr] || 0;
const isCompleted = dateCount >= currentHabitDailyTarget;
if (isCompleted) {
dateCell.classList.add('completed');
}
// Use the new display function for consistent formatting
updateDateCellDisplay(dateCell, dateStr, dateCount);
if (dateStr === today) {
dateCell.classList.add('today');
}
@@ -261,41 +288,54 @@ function closeModal() {
}
async function toggleCompletionForDate(event, habitId, date) {
const cell = event.target;
// Find the actual date cell, even if clicked on child elements
let cell = event.target;
if (!cell.classList.contains('date-cell')) {
cell = cell.closest('.date-cell');
}
if (!cell) return; // Safety check
let response;
let data;
if (cell.classList.contains('completed')) {
// Mark as uncompleted
const currentCount = currentHabitCompletedDates[date] || 0;
const shouldDecrement = event.shiftKey || event.ctrlKey || currentCount >= currentHabitDailyTarget;
if (shouldDecrement && currentCount > 0) {
// Decrement completion count
response = await fetch(`/habits/${habitId}/uncomplete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ date: date })
});
data = await response.json();
if (response.ok) {
cell.classList.remove('completed');
// Update local completed dates array
const index = currentHabitCompletedDates.indexOf(date);
if (index > -1) {
currentHabitCompletedDates.splice(index, 1);
}
}
} else {
// Mark as completed
// Increment completion count
response = await fetch(`/habits/${habitId}/complete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ date: date })
});
data = await response.json();
if (response.ok) {
}
data = await response.json();
if (response.ok) {
// Update local completed dates object
currentHabitCompletedDates[date] = data.current_count;
// Update cell appearance
const newCount = data.current_count;
const isCompleted = newCount >= currentHabitDailyTarget;
if (isCompleted) {
cell.classList.add('completed');
// Update local completed dates array
if (!currentHabitCompletedDates.includes(date)) {
currentHabitCompletedDates.push(date);
}
} else {
cell.classList.remove('completed');
}
// Update cell text display
updateDateCellDisplay(cell, date, newCount);
}
}
@@ -381,37 +421,27 @@ async function deleteHabitFromModal() {
}
}
async function toggleTodayCompletion(habitId, date, buttonElement) {
async function toggleTodayCompletion(habitId, date, buttonElement, dailyTarget = 1) {
try {
const isCurrentlyCompleted = buttonElement.classList.contains('completed-today');
let response;
if (isCurrentlyCompleted) {
// Mark as uncompleted
response = await fetch(`/habits/${habitId}/uncomplete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ date: date })
});
} else {
// Mark as completed
response = await fetch(`/habits/${habitId}/complete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ date: date })
});
}
// Always increment completion count
const response = await fetch(`/habits/${habitId}/complete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ date: date })
});
const data = await response.json();
if (response.ok) {
// Update button appearance
if (isCurrentlyCompleted) {
buttonElement.classList.remove('completed-today');
buttonElement.classList.add('not-completed-today');
} else {
buttonElement.classList.remove('not-completed-today');
buttonElement.classList.add('completed-today');
const newCount = data.current_count;
const isCompleted = newCount >= dailyTarget;
// Update button appearance and text
if (dailyTarget > 1) {
buttonElement.innerHTML = `${newCount}/${dailyTarget}`;
}
buttonElement.className = isCompleted ? 'completed-today' : 'not-completed-today';
// Refresh the date grid to show updated completion status
fetchHabits();
} else {
@@ -459,10 +489,15 @@ async function updateHabitColor() {
}
function updateModalColors(color) {
// Update completed date cells in modal
const completedCells = modalDateGrid.querySelectorAll('.date-cell.completed');
completedCells.forEach(cell => {
cell.style.backgroundColor = color;
// Update all date cells in modal to use new color
const allCells = modalDateGrid.querySelectorAll('.date-cell');
allCells.forEach(cell => {
const dateStr = cell.dataset.date;
if (dateStr) {
const dateCount = currentHabitCompletedDates[dateStr] || 0;
// Re-apply styling with new color
applyModalCompletionStyling(cell, dateCount, currentHabitDailyTarget, color);
}
});
}
@@ -477,4 +512,114 @@ function getContrastColor(hexColor) {
// Return dark text for light colors, light text for dark colors
return luminance > 0.5 ? '#333333' : '#ffffff';
}
async function updateDailyTarget() {
if (!currentHabitId) {
console.error('No habit selected for daily target update.');
return;
}
const newTarget = parseInt(document.getElementById('habitDailyTarget').value);
if (newTarget < 1 || newTarget > 20) {
alert('Tägliches Ziel muss zwischen 1 und 20 liegen.');
return;
}
currentHabitDailyTarget = newTarget;
try {
const response = await fetch(`/habits/${currentHabitId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ daily_target: newTarget })
});
const data = await response.json();
if (response.ok) {
// Re-render modal calendar with new target
renderModalCalendar();
// Refresh habits list to show new target
fetchHabits();
} else {
console.error('Failed to update daily target:', data.error);
}
} catch (error) {
console.error('Error updating daily target:', error);
}
}
function updateDateCellDisplay(cell, date, count) {
const day = date.split('-')[2]; // Get day from YYYY-MM-DD format
// Clear any existing content first
cell.innerHTML = '';
// Apply gradient styling for modal cells
applyModalCompletionStyling(cell, count, currentHabitDailyTarget, currentHabitColor);
if (currentHabitDailyTarget > 1) {
// Create structured display with date on top, counter below
const dayDiv = document.createElement('div');
dayDiv.className = 'date-day';
dayDiv.textContent = parseInt(day);
const counterDiv = document.createElement('div');
counterDiv.className = 'date-counter';
counterDiv.textContent = `${count}/${currentHabitDailyTarget}`;
cell.appendChild(dayDiv);
cell.appendChild(counterDiv);
} else {
cell.textContent = parseInt(day);
}
}
function applyCompletionStyling(element, currentCount, targetCount, color) {
// Remove existing classes
element.classList.remove('completed', 'partial');
if (currentCount === 0) {
// No completion - default background
return;
} else if (currentCount >= targetCount) {
// Fully completed - solid color
element.classList.add('completed');
} else {
// Partially completed - gradient
element.classList.add('partial');
const percentage = Math.round((currentCount / targetCount) * 100);
element.style.setProperty('--completion-percentage', `${percentage}%`);
element.style.setProperty('--habit-color', color);
}
}
function applyModalCompletionStyling(element, currentCount, targetCount, color) {
// Remove existing classes
element.classList.remove('completed', 'partial');
if (currentCount === 0) {
// No completion - default background and text
element.style.removeProperty('color');
return;
} else if (currentCount >= targetCount) {
// Fully completed - solid color with contrast text
element.classList.add('completed');
const contrastColor = getContrastColor(color);
element.style.setProperty('color', contrastColor);
} else {
// Partially completed - gradient with smart text color
element.classList.add('partial');
const percentage = Math.round((currentCount / targetCount) * 100);
element.style.setProperty('--completion-percentage', `${percentage}%`);
element.style.setProperty('--current-habit-color', color);
// For partial completion, use contrast color if more than 50% completed
if (percentage > 50) {
const contrastColor = getContrastColor(color);
element.style.setProperty('color', contrastColor);
} else {
// Use default text color for low completion
element.style.setProperty('color', '#e0e0e0');
}
}
}