All files / components CreateHabitModal.jsx

65.82% Statements 52/79
49.15% Branches 29/59
28.57% Functions 8/28
65.82% Lines 52/79

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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415                1x         1x                       1x                     12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x   12x   12x 1x   1x 1x 1x             12x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     12x 2x 2x 1x 1x   1x       1x 2x         1x 1x     1x     1x       1x     12x               12x   12x                                                                                   1x                                                                                                                                                                                                                                                                                                                           110x                                                                                                                                   110x                                                              
import { useState } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { X, ChevronDown, ChevronUp, Clock, Calendar } from "lucide-react"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { habitsApi } from "../api/habits"
import { format } from "date-fns"
import clsx from "clsx"
 
const COLORS = [
  "#6366f1", "#8b5cf6", "#d946ef", "#ec4899", "#f43f5e",
  "#f97316", "#eab308", "#22c55e", "#14b8a6", "#0ea5e9",
]
 
const ICON_CATEGORIES = [
  { name: "Спорт", icons: ["💪", "🏃", "🚴", "🏊", "🧘", "⚽", "🏀", "🎾"] },
  { name: "Здоровье", icons: ["💊", "💉", "🩺", "🧠", "😴", "💤", "🦷", "👁️"] },
  { name: "Продуктивность", icons: ["📚", "📖", "✏️", "💻", "🎯", "📝", "📅", "⏰"] },
  { name: "Дом", icons: ["🏠", "🧹", "🧺", "🍳", "🛒", "🔧", "🪴"] },
  { name: "Финансы", icons: ["💰", "💳", "📊", "💵", "🏦"] },
  { name: "Социальное", icons: ["👥", "💬", "📞", "👪", "❤️"] },
  { name: "Хобби", icons: ["🎨", "🎵", "🎸", "🎮", "📷", "✈️", "🚗"] },
  { name: "Еда/вода", icons: ["🥗", "🍎", "🥤", "☕", "🍽️", "💧"] },
  { name: "Разное", icons: ["⭐", "🎉", "✨", "🔥", "🌟", "💎", "🎁"] },
]
 
const DAYS = [
  { id: 1, short: "Пн", full: "Понедельник" },
  { id: 2, short: "Вт", full: "Вторник" },
  { id: 3, short: "Ср", full: "Среда" },
  { id: 4, short: "Чт", full: "Четверг" },
  { id: 5, short: "Пт", full: "Пятница" },
  { id: 6, short: "Сб", full: "Суббота" },
  { id: 7, short: "Вс", full: "Воскресенье" },
]
 
export default function CreateHabitModal({ open, onClose }) {
  const [name, setName] = useState("")
  const [description, setDescription] = useState("")
  const [color, setColor] = useState(COLORS[0])
  const [icon, setIcon] = useState("✨")
  const [frequency, setFrequency] = useState("daily")
  const [targetDays, setTargetDays] = useState([1, 2, 3, 4, 5, 6, 7])
  const [intervalDays, setIntervalDays] = useState(2)
  const [reminderTime, setReminderTime] = useState("")
  const [startDate, setStartDate] = useState(format(new Date(), "yyyy-MM-dd"))
  const [error, setError] = useState("")
  const [showAllIcons, setShowAllIcons] = useState(false)
  
  const queryClient = useQueryClient()
 
  const mutation = useMutation({
    mutationFn: (data) => habitsApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["habits"] })
      queryClient.invalidateQueries({ queryKey: ["stats"] })
      handleClose()
    },
    onError: (err) => {
      setError(err.response?.data?.error || "Ошибка создания")
    },
  })
 
  const handleClose = () => {
    setName("")
    setDescription("")
    setColor(COLORS[0])
    setIcon("✨")
    setFrequency("daily")
    setTargetDays([1, 2, 3, 4, 5, 6, 7])
    setIntervalDays(2)
    setReminderTime("")
    setStartDate(format(new Date(), "yyyy-MM-dd"))
    setError("")
    setShowAllIcons(false)
    onClose()
  }
 
  const handleSubmit = (e) => {
    e.preventDefault()
    if (!name.trim()) {
      setError("Введи название привычки")
      return
    }
    Iif (frequency === "weekly" && targetDays.length === 0) {
      setError("Выбери хотя бы один день недели")
      return
    }
    const interval = parseInt(intervalDays) || 0
    Iif (frequency === "interval" && (interval < 2 || interval > 30)) {
      setError("Интервал должен быть от 2 до 30 дней")
      return
    }
    
    const data = { name, description, color, icon, frequency, start_date: startDate }
    Iif (frequency === "weekly") {
      data.target_days = targetDays
    }
    Iif (frequency === "interval") {
      data.target_count = parseInt(intervalDays)
    }
    Iif (reminderTime) {
      data.reminder_time = reminderTime
    }
    
    mutation.mutate(data)
  }
 
  const toggleDay = (dayId) => {
    setTargetDays(prev => 
      prev.includes(dayId)
        ? prev.filter(d => d !== dayId)
        : [...prev, dayId].sort((a, b) => a - b)
    )
  }
 
  const popularIcons = ["✨", "💪", "📚", "🏃", "💧", "🧘", "💤", "🎯", "✏️", "🍎"]
 
  return (
    <AnimatePresence>
      {open && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={handleClose}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-40"
          />
          <motion.div
            initial={{ opacity: 0, y: 100 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 100 }}
            className="fixed bottom-0 left-0 right-0 z-50 p-4 sm:p-0 sm:flex sm:items-center sm:justify-center sm:inset-0"
          >
            <div className="bg-white dark:bg-gray-900 rounded-2xl sm:rounded-2xl w-full max-w-md max-h-[85vh] overflow-auto">
              <div className="sticky top-0 bg-white dark:bg-gray-900 border-b border-gray-100 dark:border-gray-800 px-4 py-3 flex items-center justify-between">
                <h2 className="text-lg font-semibold">Новая привычка</h2>
                <button
                  onClick={handleClose}
                  className="p-2 text-gray-400 dark:text-gray-500 hover:text-gray-600 rounded-xl hover:bg-gray-100 dark:hover:bg-gray-800 dark:bg-gray-800"
                >
                  <X size={20} />
                </button>
              </div>
 
              <form onSubmit={handleSubmit} className="p-4 space-y-4">
                {error && (
                  <div className="p-3 rounded-xl bg-red-50 text-red-600 text-sm">
                    {error}
                  </div>
                )}
 
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5">
                    Название
                  </label>
                  <input
                    type="text"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    className="input"
                    placeholder="Например: Пить воду"
                    autoFocus
                  />
                </div>
 
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5">
                    Описание (опционально)
                  </label>
                  <input
                    type="text"
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    className="input"
                    placeholder="8 стаканов в день"
                  />
                </div>
 
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Периодичность
                  </label>
                  <div className="flex gap-2">
                    <button
                      type="button"
                      onClick={() => setFrequency("daily")}
                      className={clsx(
                        "flex-1 py-2.5 px-3 rounded-xl font-medium text-sm transition-all",
                        frequency === "daily"
                          ? "bg-primary-500 text-white shadow-lg shadow-primary-500/30"
                          : "bg-gray-100 dark:bg-gray-800 text-gray-600 hover:bg-gray-200"
                      )}
                    >
                      Ежедневно
                    </button>
                    <button
                      type="button"
                      onClick={() => setFrequency("weekly")}
                      className={clsx(
                        "flex-1 py-2.5 px-3 rounded-xl font-medium text-sm transition-all",
                        frequency === "weekly"
                          ? "bg-primary-500 text-white shadow-lg shadow-primary-500/30"
                          : "bg-gray-100 dark:bg-gray-800 text-gray-600 hover:bg-gray-200"
                      )}
                    >
                      По дням
                    </button>
                    <button
                      type="button"
                      onClick={() => setFrequency("interval")}
                      className={clsx(
                        "flex-1 py-2.5 px-3 rounded-xl font-medium text-sm transition-all",
                        frequency === "interval"
                          ? "bg-primary-500 text-white shadow-lg shadow-primary-500/30"
                          : "bg-gray-100 dark:bg-gray-800 text-gray-600 hover:bg-gray-200"
                      )}
                    >
                      Интервал
                    </button>
                  </div>
                </div>
 
                {frequency === "weekly" && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: "auto" }}
                    exit={{ opacity: 0, height: 0 }}
                  >
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Дни недели
                    </label>
                    <div className="flex gap-1.5">
                      {DAYS.map((day) => (
                        <button
                          key={day.id}
                          type="button"
                          onClick={() => toggleDay(day.id)}
                          className={clsx(
                            "flex-1 py-2 rounded-lg font-medium text-sm transition-all",
                            targetDays.includes(day.id)
                              ? "bg-primary-500 text-white shadow-md"
                              : "bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400 dark:text-gray-500 hover:bg-gray-200"
                          )}
                        >
                          {day.short}
                        </button>
                      ))}
                    </div>
                  </motion.div>
                )}
 
                {frequency === "interval" && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: "auto" }}
                    exit={{ opacity: 0, height: 0 }}
                  >
                    <div className="flex items-center gap-3">
                      <span className="text-gray-500 dark:text-gray-400 dark:text-gray-500">Каждые</span>
                      <input
                        type="number"
                        min="2"
                        max="30"
                        value={intervalDays}
                        onChange={(e) => setIntervalDays(e.target.value === "" ? "" : parseInt(e.target.value) || "")}
                        className="input w-20 text-center"
                      />
                      <span className="text-gray-500 dark:text-gray-400 dark:text-gray-500">дней</span>
                    </div>
                  </motion.div>
                )}
 
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Дата начала
                  </label>
                  <div className="relative">
                    <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500" size={18} />
                    <input
                      type="date"
                      value={startDate}
                      onChange={(e) => setStartDate(e.target.value)}
                      className="input pl-10"
                    />
                  </div>
                  <p className="text-xs text-gray-500 dark:text-gray-400 dark:text-gray-500 mt-1">
                    {frequency === "interval" 
                      ? "Интервал считается от этой даты"
                      : "Привычка появится начиная с этой даты"}
                  </p>
                </div>
 
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Напоминание (опционально)
                  </label>
                  <div className="relative">
                    <Clock className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500" size={18} />
                    <input
                      type="time"
                      value={reminderTime}
                      onChange={(e) => setReminderTime(e.target.value)}
                      className="input pl-10"
                    />
                  </div>
                  <p className="text-xs text-gray-500 dark:text-gray-400 dark:text-gray-500 mt-1">
                    Получишь напоминание в Telegram в указанное время
                  </p>
                </div>
 
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Иконка
                  </label>
                  <div className="flex flex-wrap gap-2">
                    {popularIcons.map((ic) => (
                      <button
                        key={ic}
                        type="button"
                        onClick={() => setIcon(ic)}
                        className={clsx(
                          "w-10 h-10 rounded-xl flex items-center justify-center text-xl transition-all",
                          icon === ic
                            ? "bg-primary-100 ring-2 ring-primary-500"
                            : "bg-gray-100 dark:bg-gray-800 hover:bg-gray-200"
                        )}
                      >
                        {ic}
                      </button>
                    ))}
                  </div>
                  
                  <button
                    type="button"
                    onClick={() => setShowAllIcons(!showAllIcons)}
                    className="mt-2 flex items-center gap-1 text-sm text-primary-600 hover:text-primary-700"
                  >
                    {showAllIcons ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
                    {showAllIcons ? "Скрыть" : "Все иконки"}
                  </button>
 
                  <AnimatePresence>
                    {showAllIcons && (
                      <motion.div
                        initial={{ opacity: 0, height: 0 }}
                        animate={{ opacity: 1, height: "auto" }}
                        exit={{ opacity: 0, height: 0 }}
                        className="mt-3 space-y-3"
                      >
                        {ICON_CATEGORIES.map((category) => (
                          <div key={category.name}>
                            <p className="text-xs text-gray-500 dark:text-gray-400 dark:text-gray-500 mb-1.5">{category.name}</p>
                            <div className="flex flex-wrap gap-1.5">
                              {category.icons.map((ic) => (
                                <button
                                  key={ic}
                                  type="button"
                                  onClick={() => setIcon(ic)}
                                  className={clsx(
                                    "w-9 h-9 rounded-lg flex items-center justify-center text-lg transition-all",
                                    icon === ic
                                      ? "bg-primary-100 ring-2 ring-primary-500"
                                      : "bg-gray-100 dark:bg-gray-800 hover:bg-gray-200"
                                  )}
                                >
                                  {ic}
                                </button>
                              ))}
                            </div>
                          </div>
                        ))}
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
 
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Цвет
                  </label>
                  <div className="flex flex-wrap gap-2">
                    {COLORS.map((c) => (
                      <button
                        key={c}
                        type="button"
                        onClick={() => setColor(c)}
                        className={clsx(
                          "w-8 h-8 rounded-full transition-all",
                          color === c ? "ring-2 ring-offset-2 ring-gray-400 scale-110" : ""
                        )}
                        style={{ backgroundColor: c }}
                      />
                    ))}
                  </div>
                </div>
 
                <div className="pt-2">
                  <button
                    type="submit"
                    disabled={mutation.isPending}
                    className="btn btn-primary w-full"
                  >
                    {mutation.isPending ? "Создаём..." : "Создать привычку"}
                  </button>
                </div>
              </form>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  )
}