working version 3

This commit is contained in:
Harivansh Rathi 2024-11-18 13:22:55 -05:00
parent 1fab739a19
commit 081963cc21
3 changed files with 234 additions and 118 deletions

BIN
habits.db

Binary file not shown.

View file

@ -19,6 +19,12 @@ export function Calendar({
}: CalendarProps) { }: CalendarProps) {
const daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; const daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const getFirstDayOfMonth = (year: number, month: number) => {
const date = new Date(year, month, 1);
// Convert Sunday (0) to 6 for our Monday-based week
return date.getDay() === 0 ? 6 : date.getDay() - 1;
};
return ( return (
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-lg p-6"> <div className="bg-white dark:bg-gray-900 rounded-lg shadow-lg p-6">
<div className="flex items-center justify-between mb-8"> <div className="flex items-center justify-between mb-8">
@ -47,21 +53,67 @@ export function Calendar({
{day} {day}
</div> </div>
))} ))}
{Array.from({ length: getDaysInMonth(currentMonth.getFullYear(), currentMonth.getMonth()) }).map((_, index) => {
const date = new Date( {(() => {
currentMonth.getFullYear(), const year = currentMonth.getFullYear();
currentMonth.getMonth(), const month = currentMonth.getMonth();
index + 1 const firstDayOfMonth = getFirstDayOfMonth(year, month);
).toISOString().split('T')[0]; const daysInMonth = getDaysInMonth(year, month);
const daysInPrevMonth = getDaysInMonth(year, month - 1);
// Calculate days to show
const days = [];
// Previous month days
for (let i = 0; i < firstDayOfMonth; i++) {
const day = daysInPrevMonth - firstDayOfMonth + i + 1;
const date = new Date(year, month - 1, day).toISOString().split('T')[0];
days.push({
date,
dayNumber: day,
isCurrentMonth: false
});
}
// Current month days
for (let i = 1; i <= daysInMonth; i++) {
const date = new Date(year, month, i).toISOString().split('T')[0];
days.push({
date,
dayNumber: i,
isCurrentMonth: true
});
}
// Next month days to complete the grid
const remainingDays = 42 - days.length; // 6 rows * 7 days
for (let i = 1; i <= remainingDays; i++) {
const date = new Date(year, month + 1, i).toISOString().split('T')[0];
days.push({
date,
dayNumber: i,
isCurrentMonth: false
});
}
return days.map(({ date, dayNumber, isCurrentMonth }) => {
const completedHabits = getCompletedHabitsForDate(date); const completedHabits = getCompletedHabitsForDate(date);
const incompleteHabits = habits.filter(habit => !habit.completedDates.includes(date)); const incompleteHabits = habits.filter(habit => !habit.completedDates.includes(date));
return ( return (
<div <div
key={date} key={date}
className="border dark:border-gray-700 rounded-lg p-3 min-h-[80px] relative group hover:shadow-md transition-shadow duration-200" className={`border dark:border-gray-700 rounded-lg p-3 min-h-[80px] relative group hover:shadow-md transition-shadow duration-200 ${
!isCurrentMonth ? 'bg-gray-50 dark:bg-gray-800/50' : ''
}`}
> >
<span className="text-sm font-medium dark:text-white">{index + 1}</span> <span className={`text-sm font-medium ${
isCurrentMonth
? 'dark:text-white'
: 'text-gray-400 dark:text-gray-500'
}`}>
{dayNumber}
</span>
{habits.length > 0 && ( {habits.length > 0 && (
<div className="absolute bottom-3 left-1/2 transform -translate-x-1/2"> <div className="absolute bottom-3 left-1/2 transform -translate-x-1/2">
<div className="relative"> <div className="relative">
@ -109,7 +161,8 @@ export function Calendar({
)} )}
</div> </div>
); );
})} });
})()}
</div> </div>
</div> </div>
); );

View file

@ -1,4 +1,4 @@
import React from 'react'; import React, { useEffect } from 'react';
import { Trash2 } from 'lucide-react'; import { Trash2 } from 'lucide-react';
import { Habit } from '../types'; import { Habit } from '../types';
@ -13,58 +13,111 @@ interface HabitListProps {
} }
const calculateStreak = (completedDates: string[]): { currentStreak: number; bestStreak: number } => { const calculateStreak = (completedDates: string[]): { currentStreak: number; bestStreak: number } => {
if (completedDates.length === 0) return { currentStreak: 0, bestStreak: 0 }; if (!completedDates || completedDates.length === 0) {
return { currentStreak: 0, bestStreak: 0 };
const sortedDates = [...completedDates].sort((a, b) =>
new Date(a).getTime() - new Date(b).getTime()
);
let currentStreak = 1;
let bestStreak = 1;
let tempStreak = 1;
// Check if the last completion was today or yesterday
const lastDate = new Date(sortedDates[sortedDates.length - 1]);
const today = new Date();
today.setHours(0, 0, 0, 0);
lastDate.setHours(0, 0, 0, 0);
const diffDays = Math.floor((today.getTime() - lastDate.getTime()) / (24 * 60 * 60 * 1000));
// If the last completion was more than a day ago, current streak is 0
if (diffDays > 1) {
currentStreak = 0;
} }
// Calculate streaks // Get today's date at midnight
for (let i = 1; i < sortedDates.length; i++) { const today = new Date();
const prevDate = new Date(sortedDates[i - 1]); today.setHours(0, 0, 0, 0);
const currDate = new Date(sortedDates[i]); const todayStr = today.toISOString().split('T')[0];
prevDate.setHours(0, 0, 0, 0);
currDate.setHours(0, 0, 0, 0);
const diffTime = currDate.getTime() - prevDate.getTime(); // Sort dates in descending order (most recent first)
const diffDays = Math.floor(diffTime / (24 * 60 * 60 * 1000)); const sortedDates = [...completedDates]
.filter(date => !isNaN(new Date(date).getTime()))
.sort((a, b) => new Date(b).getTime() - new Date(a).getTime());
let currentStreak = 0;
let bestStreak = 0;
let tempStreak = 0;
// First, check if today is completed
const hasTodayCompleted = sortedDates.includes(todayStr);
if (!hasTodayCompleted) {
// If today isn't completed, current streak is 0
currentStreak = 0;
} else {
// Start counting current streak from today
let checkDate = new Date(today);
currentStreak = 1; // Start with 1 for today
// Check previous days
while (true) {
// Move to previous day
checkDate.setDate(checkDate.getDate() - 1);
const dateStr = checkDate.toISOString().split('T')[0];
if (sortedDates.includes(dateStr)) {
currentStreak++;
} else {
break; // Break streak if a day is missed
}
}
}
// Calculate best streak
for (let i = 0; i < sortedDates.length; i++) {
const currentDate = new Date(sortedDates[i]);
if (i === 0) {
tempStreak = 1;
} else {
const prevDate = new Date(sortedDates[i - 1]);
const diffDays = Math.floor(
(prevDate.getTime() - currentDate.getTime()) / (1000 * 60 * 60 * 24)
);
if (diffDays === 1) { if (diffDays === 1) {
tempStreak++; tempStreak++;
bestStreak = Math.max(bestStreak, tempStreak);
} else if (diffDays === 0) { } else if (diffDays === 0) {
// Same day completions don't affect streak // Same day, skip
continue; continue;
} else { } else {
// Reset streak on gap
bestStreak = Math.max(bestStreak, tempStreak);
tempStreak = 1; tempStreak = 1;
} }
} }
// Current streak should be the same as tempStreak if the last completion was today or yesterday
if (diffDays <= 1) {
currentStreak = tempStreak;
} }
// Final check for best streak
bestStreak = Math.max(bestStreak, tempStreak);
// Also check if current streak is the best
bestStreak = Math.max(bestStreak, currentStreak);
return { currentStreak, bestStreak }; return { currentStreak, bestStreak };
}; };
const getCurrentWeekDates = () => {
// Start with Sunday (today's week)
const now = new Date();
const sunday = new Date(now);
sunday.setDate(now.getDate() - now.getDay());
const weekDates = [];
for (let i = 0; i < 7; i++) {
const date = new Date(sunday);
date.setDate(sunday.getDate() + i);
// Format as YYYY-MM-DD
const formattedDate = date.toISOString().split('T')[0];
weekDates.push(formattedDate);
}
return weekDates;
};
// If you want Monday first, rotate the array
const currentWeek = (() => {
const dates = getCurrentWeekDates();
// Move Sunday to the end
const sunday = dates.shift()!;
dates.push(sunday);
return dates;
})();
const daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
export function HabitList({ export function HabitList({
habits, habits,
currentWeek, currentWeek,
@ -74,25 +127,35 @@ export function HabitList({
onDeleteHabit, onDeleteHabit,
onUpdateStreak, onUpdateStreak,
}: HabitListProps) { }: HabitListProps) {
useEffect(() => {
console.log('Current week dates:',
currentWeek.map(date =>
`${new Date(date).toLocaleDateString()} (${daysOfWeek[new Date(date).getDay() === 0 ? 6 : new Date(date).getDay() - 1]})`
)
);
}, []);
return ( return (
<table className="w-full"> <table className="w-full">
<thead> <thead>
<tr> <tr>
<th className="px-4 py-2 text-left dark:text-white">Habit</th> <th className="px-4 py-2 text-left dark:text-white">Habit</th>
{daysOfWeek.map((day, index) => ( {currentWeek.map((dateStr, index) => {
<th key={day} className="px-4 py-2 text-center dark:text-white"> const date = new Date(dateStr);
{day} // Ensure date is interpreted in local timezone
const displayDate = new Date(date.getTime() + date.getTimezoneOffset() * 60000);
return (
<th key={dateStr} className="px-4 py-2 text-center dark:text-white">
<div>{daysOfWeek[index]}</div>
<div className="text-xs text-gray-500 dark:text-gray-400"> <div className="text-xs text-gray-500 dark:text-gray-400">
{new Date(currentWeek[index]).getDate()} {displayDate.getDate()}
</div> </div>
</th> </th>
))} );
<th className="px-4 py-2 text-center dark:text-white"> })}
Current Streak <th className="px-4 py-2 text-center dark:text-white">Current Streak</th>
</th> <th className="px-4 py-2 text-center dark:text-white">Best Streak</th>
<th className="px-4 py-2 text-center dark:text-white">
Best Streak
</th>
<th className="px-4 py-2 text-center dark:text-white">Actions</th> <th className="px-4 py-2 text-center dark:text-white">Actions</th>
</tr> </tr>
</thead> </thead>
@ -130,12 +193,12 @@ export function HabitList({
))} ))}
<td className="px-4 py-2 text-center"> <td className="px-4 py-2 text-center">
<span className="dark:text-white font-medium"> <span className="dark:text-white font-medium">
{calculateStreak(habit.completedDates).currentStreak} {calculateStreak(habit.completedDates || []).currentStreak}
</span> </span>
</td> </td>
<td className="px-4 py-2 text-center"> <td className="px-4 py-2 text-center">
<span className="dark:text-white font-medium"> <span className="dark:text-white font-medium">
{calculateStreak(habit.completedDates).bestStreak} {calculateStreak(habit.completedDates || []).bestStreak}
</span> </span>
</td> </td>
<td className="px-4 py-2 text-center"> <td className="px-4 py-2 text-center">