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,69 +53,116 @@ export function Calendar({
{day} {day}
</div> </div>
))} ))}
{Array.from({ length: getDaysInMonth(currentMonth.getFullYear(), currentMonth.getMonth()) }).map((_, index) => {
const date = new Date(
currentMonth.getFullYear(),
currentMonth.getMonth(),
index + 1
).toISOString().split('T')[0];
const completedHabits = getCompletedHabitsForDate(date);
const incompleteHabits = habits.filter(habit => !habit.completedDates.includes(date));
return ( {(() => {
<div const year = currentMonth.getFullYear();
key={date} const month = currentMonth.getMonth();
className="border dark:border-gray-700 rounded-lg p-3 min-h-[80px] relative group hover:shadow-md transition-shadow duration-200" const firstDayOfMonth = getFirstDayOfMonth(year, month);
> const daysInMonth = getDaysInMonth(year, month);
<span className="text-sm font-medium dark:text-white">{index + 1}</span> const daysInPrevMonth = getDaysInMonth(year, month - 1);
{habits.length > 0 && (
<div className="absolute bottom-3 left-1/2 transform -translate-x-1/2"> // Calculate days to show
<div className="relative"> const days = [];
<div
className={`h-3 w-3 ${ // Previous month days
completedHabits.length > 0 for (let i = 0; i < firstDayOfMonth; i++) {
? 'bg-green-500 shadow-sm shadow-green-200' const day = daysInPrevMonth - firstDayOfMonth + i + 1;
: 'bg-gray-300 dark:bg-gray-600' const date = new Date(year, month - 1, day).toISOString().split('T')[0];
} rounded-full transition-colors duration-200`} days.push({
/> date,
<div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-3 hidden group-hover:block"> dayNumber: day,
<div className="bg-white dark:bg-gray-800 text-sm rounded-lg shadow-lg p-4 border dark:border-gray-700 min-w-[200px]"> isCurrentMonth: false
{completedHabits.length > 0 && ( });
<div className="mb-3"> }
<span className="text-green-500 font-semibold block mb-1">
Completed // Current month days
</span> for (let i = 1; i <= daysInMonth; i++) {
<ul className="space-y-1"> const date = new Date(year, month, i).toISOString().split('T')[0];
{completedHabits.map(habit => ( days.push({
<li key={habit.id} className="text-gray-600 dark:text-gray-300"> date,
{habit.name} dayNumber: i,
</li> isCurrentMonth: true
))} });
</ul> }
</div>
)} // Next month days to complete the grid
{incompleteHabits.length > 0 && ( const remainingDays = 42 - days.length; // 6 rows * 7 days
<div> for (let i = 1; i <= remainingDays; i++) {
<span className="text-red-500 font-semibold block mb-1"> const date = new Date(year, month + 1, i).toISOString().split('T')[0];
Pending days.push({
</span> date,
<ul className="space-y-1"> dayNumber: i,
{incompleteHabits.map(habit => ( isCurrentMonth: false
<li key={habit.id} className="text-gray-600 dark:text-gray-300"> });
{habit.name} }
</li>
))} return days.map(({ date, dayNumber, isCurrentMonth }) => {
</ul> const completedHabits = getCompletedHabitsForDate(date);
</div> const incompleteHabits = habits.filter(habit => !habit.completedDates.includes(date));
)}
return (
<div
key={date}
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 ${
isCurrentMonth
? 'dark:text-white'
: 'text-gray-400 dark:text-gray-500'
}`}>
{dayNumber}
</span>
{habits.length > 0 && (
<div className="absolute bottom-3 left-1/2 transform -translate-x-1/2">
<div className="relative">
<div
className={`h-3 w-3 ${
completedHabits.length > 0
? 'bg-green-500 shadow-sm shadow-green-200'
: 'bg-gray-300 dark:bg-gray-600'
} rounded-full transition-colors duration-200`}
/>
<div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-3 hidden group-hover:block">
<div className="bg-white dark:bg-gray-800 text-sm rounded-lg shadow-lg p-4 border dark:border-gray-700 min-w-[200px]">
{completedHabits.length > 0 && (
<div className="mb-3">
<span className="text-green-500 font-semibold block mb-1">
Completed
</span>
<ul className="space-y-1">
{completedHabits.map(habit => (
<li key={habit.id} className="text-gray-600 dark:text-gray-300">
{habit.name}
</li>
))}
</ul>
</div>
)}
{incompleteHabits.length > 0 && (
<div>
<span className="text-red-500 font-semibold block mb-1">
Pending
</span>
<ul className="space-y-1">
{incompleteHabits.map(habit => (
<li key={habit.id} className="text-gray-600 dark:text-gray-300">
{habit.name}
</li>
))}
</ul>
</div>
)}
</div>
</div> </div>
</div> </div>
</div> </div>
</div> )}
)} </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());
if (diffDays === 1) { let currentStreak = 0;
tempStreak++; let bestStreak = 0;
bestStreak = Math.max(bestStreak, tempStreak); let tempStreak = 0;
} else if (diffDays === 0) {
// Same day completions don't affect streak // First, check if today is completed
continue; const hasTodayCompleted = sortedDates.includes(todayStr);
} else {
tempStreak = 1; 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
}
} }
} }
// Current streak should be the same as tempStreak if the last completion was today or yesterday // Calculate best streak
if (diffDays <= 1) { for (let i = 0; i < sortedDates.length; i++) {
currentStreak = tempStreak; 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) {
tempStreak++;
} else if (diffDays === 0) {
// Same day, skip
continue;
} else {
// Reset streak on gap
bestStreak = Math.max(bestStreak, tempStreak);
tempStreak = 1;
}
}
} }
// 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
<div className="text-xs text-gray-500 dark:text-gray-400"> const displayDate = new Date(date.getTime() + date.getTimezoneOffset() * 60000);
{new Date(currentWeek[index]).getDate()}
</div> return (
</th> <th key={dateStr} className="px-4 py-2 text-center dark:text-white">
))} <div>{daysOfWeek[index]}</div>
<th className="px-4 py-2 text-center dark:text-white"> <div className="text-xs text-gray-500 dark:text-gray-400">
Current Streak {displayDate.getDate()}
</th> </div>
<th className="px-4 py-2 text-center dark:text-white"> </th>
Best Streak );
</th> })}
<th className="px-4 py-2 text-center dark:text-white">Current 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">