All files / components LogHabitModal.jsx

58.33% Statements 28/48
56.52% Branches 26/46
50% Functions 8/16
64.28% Lines 27/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210                6x 6x 6x   6x 6x 6x 6x       6x 6x 6x       6x     6x 155x     6x           6x                           6x 6x   6x   5x                         1x                                                                                                             35x                   30x         155x 155x 155x 155x   155x                                                                                                                                
import { useState, useMemo } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { X, ChevronLeft, ChevronRight, Check } from 'lucide-react'
import { format, startOfMonth, endOfMonth, eachDayOfInterval, isSameDay, isFuture, startOfDay, subMonths, addMonths, isToday } from 'date-fns'
import { ru } from 'date-fns/locale'
import clsx from 'clsx'
 
export default function LogHabitModal({ open, onClose, habit, completedDates = [], onLogDate }) {
  const [currentMonth, setCurrentMonth] = useState(new Date())
  const [selectedDate, setSelectedDate] = useState(null)
  const [isLogging, setIsLogging] = useState(false)
 
  const days = useMemo(() => {
    const start = startOfMonth(currentMonth)
    const end = endOfMonth(currentMonth)
    return eachDayOfInterval({ start, end })
  }, [currentMonth])
 
  // Convert completedDates to a Set for faster lookup
  const completedSet = useMemo(() => {
    const set = new Set()
    completedDates.forEach(d => {
      const dateStr = typeof d === 'string' ? d.split('T')[0] : format(d, 'yyyy-MM-dd')
      set.add(dateStr)
    })
    return set
  }, [completedDates])
 
  const isDateCompleted = (date) => {
    return completedSet.has(format(date, 'yyyy-MM-dd'))
  }
 
  const handleDateClick = (date) => {
    if (isFuture(startOfDay(date))) return
    if (isDateCompleted(date)) return
    setSelectedDate(date)
  }
 
  const handleConfirm = async () => {
    if (!selectedDate) return
    setIsLogging(true)
    try {
      await onLogDate(habit.id, format(selectedDate, 'yyyy-MM-dd'))
      onClose()
    } catch (error) {
      console.error('Failed to log habit:', error)
    } finally {
      setIsLogging(false)
    }
  }
 
  // Get first day of week offset
  const firstDayOfMonth = startOfMonth(currentMonth)
  const startOffset = (firstDayOfMonth.getDay() + 6) % 7 // Monday = 0
 
  if (!open) return null
 
  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
        onClick={onClose}
      >
        <motion.div
          initial={{ opacity: 0, scale: 0.95, y: 20 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.95, y: 20 }}
          onClick={e => e.stopPropagation()}
          className="bg-white dark:bg-gray-900 rounded-3xl shadow-2xl w-full max-w-sm overflow-hidden"
        >
          {/* Header */}
          <div className="p-5 border-b border-gray-100 dark:border-gray-800 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div
                className="w-10 h-10 rounded-xl flex items-center justify-center text-xl"
                style={{ backgroundColor: habit?.color + '20' }}
              >
                {habit?.icon || '✨'}
              </div>
              <div>
                <h2 className="text-lg font-display font-bold text-gray-900 dark:text-white">Отметить привычку</h2>
                <p className="text-sm text-gray-500 dark:text-gray-400 dark:text-gray-500">{habit?.name}</p>
              </div>
            </div>
            <button
              onClick={onClose}
              className="p-2 text-gray-400 dark:text-gray-500 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800 dark:bg-gray-800 rounded-xl transition-colors"
            >
              <X size={20} />
            </button>
          </div>
 
          {/* Calendar */}
          <div className="p-5">
            {/* Month navigation */}
            <div className="flex items-center justify-between mb-4">
              <button
                onClick={() => setCurrentMonth(m => subMonths(m, 1))}
                className="p-2 text-gray-400 dark:text-gray-500 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800 dark:bg-gray-800 rounded-xl transition-colors"
              >
                <ChevronLeft size={20} />
              </button>
              <span className="font-semibold text-gray-900 dark:text-white capitalize">
                {format(currentMonth, 'LLLL yyyy', { locale: ru })}
              </span>
              <button
                onClick={() => setCurrentMonth(m => addMonths(m, 1))}
                disabled={isSameDay(startOfMonth(currentMonth), startOfMonth(new Date()))}
                className={clsx(
                  "p-2 rounded-xl transition-colors",
                  isSameDay(startOfMonth(currentMonth), startOfMonth(new Date()))
                    ? "text-gray-200 cursor-not-allowed"
                    : "text-gray-400 dark:text-gray-500 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800 dark:bg-gray-800"
                )}
              >
                <ChevronRight size={20} />
              </button>
            </div>
 
            {/* Weekday headers */}
            <div className="grid grid-cols-7 gap-1 mb-2">
              {['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'].map(day => (
                <div key={day} className="text-center text-xs font-medium text-gray-400 dark:text-gray-500 py-2">
                  {day}
                </div>
              ))}
            </div>
 
            {/* Calendar grid */}
            <div className="grid grid-cols-7 gap-1">
              {/* Empty cells for offset */}
              {Array.from({ length: startOffset }).map((_, i) => (
                <div key={`offset-${i}`} className="aspect-square" />
              ))}
              
              {/* Days */}
              {days.map(day => {
                const completed = isDateCompleted(day)
                const future = isFuture(startOfDay(day))
                const selected = selectedDate && isSameDay(day, selectedDate)
                const today = isToday(day)
 
                return (
                  <button
                    key={day.toISOString()}
                    onClick={() => handleDateClick(day)}
                    disabled={future || completed}
                    className={clsx(
                      "aspect-square rounded-xl flex items-center justify-center text-sm font-medium transition-all",
                      future && "text-gray-200 cursor-not-allowed",
                      completed && "bg-green-100 text-green-600 cursor-default",
                      selected && !completed && "bg-primary-500 text-white shadow-lg shadow-primary-500/30",
                      !future && !completed && !selected && "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 dark:bg-gray-800",
                      today && !selected && !completed && "ring-2 ring-primary-200"
                    )}
                  >
                    {completed ? (
                      <Check size={16} className="text-green-600" />
                    ) : (
                      format(day, 'd')
                    )}
                  </button>
                )
              })}
            </div>
 
            {/* Selected date info */}
            {selectedDate && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="mt-4 p-3 bg-primary-50 rounded-xl text-center"
              >
                <p className="text-sm text-primary-700">
                  Выбрано: <span className="font-semibold">{format(selectedDate, 'd MMMM yyyy', { locale: ru })}</span>
                </p>
              </motion.div>
            )}
          </div>
 
          {/* Actions */}
          <div className="p-5 pt-0 flex gap-3">
            <button
              onClick={onClose}
              className="flex-1 py-3 px-4 rounded-xl font-semibold text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 transition-colors"
            >
              Отмена
            </button>
            <button
              onClick={handleConfirm}
              disabled={!selectedDate || isLogging}
              className={clsx(
                "flex-1 py-3 px-4 rounded-xl font-semibold text-white transition-all",
                selectedDate && !isLogging
                  ? "bg-primary-500 hover:bg-primary-600 shadow-lg shadow-primary-500/30"
                  : "bg-gray-300 cursor-not-allowed"
              )}
            >
              {isLogging ? 'Сохранение...' : 'Отметить'}
            </button>
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  )
}