-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhabits.html
895 lines (834 loc) · 35.4 KB
/
habits.html
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8">
<title>Daily Habits</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
width: {
'day': '40px'
}
}
},
plugins: []
}
</script>
<style>
.dragging {
opacity: 0.5;
background-color: #e5e7eb;
cursor: move;
}
tr:not(.dragging):hover {
cursor: grab;
}
tr.drag-over {
border-top: 2px solid #3b82f6;
}
.sticky-left {
position: sticky;
left: 0;
background-color: inherit;
z-index: 1;
max-width: 200px;
}
.habit-name {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
display: inline-block;
}
.table-border th, .table-border td { border: 1px solid #e5e7eb; }
.dark .table-border th, .dark .table-border td { border-color: #374151; }
.day-column {
width: 40px;
text-align: center;
}
.today-column {
border: 2px solid #f59e0b;
background-color: #fef3c7;
color: #1f2937;
}
td.day-column:hover {
background-color: #e5e7eb;
cursor: pointer;
color: #1f2937;
}
.light-bg {
color: #1f2937;
}
.dark-bg {
color: #f3f4f6;
}
.status-failed {
color: #ef4444;
}
tr:hover {
background-color: rgba(229, 231, 235, 0.2);
}
.dark tr:hover {
background-color: rgba(75, 85, 99, 0.2);
}
</style>
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100">
<header class="bg-white dark:bg-gray-800 shadow p-4 flex justify-between items-center">
<div class="flex items-center">
<h1 class="text-xl font-semibold">DailyHabits</h1>
<a href="index.html" class="ml-4 text-blue-500 hover:underline">Focus Flow</a>
</div>
<div class="flex items-center space-x-4">
<button id="exportHabitsBtn" class="p-2 border rounded dark:border-gray-700" title="Export Data">
<svg class="h-5 w-5 text-gray-700 dark:text-gray-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
</button>
<button id="importHabitsBtn" class="p-2 border rounded dark:border-gray-700" title="Import Data">
<svg class="h-5 w-5 text-gray-700 dark:text-gray-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L7 8m4-4v12" />
</svg>
</button>
<input type="file" id="importHabitsFile" accept=".json" class="hidden">
<button id="darkModeToggle" class="focus:outline-none mr-2" aria-label="Toggle Dark Mode">
<svg id="themeIcon" class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path id="sunIcon" class="dark:hidden" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 3v1m0 16v1m8.66-8.66h-1M4.34 12.34h-1M15.36 6.64l-.7.7M6.34 17.66l-.7.7M6.34 6.34l-.7-.7M15.36 17.66l-.7-.7M12 5a7 7 0 100 14 7 7 0 000-14z"></path>
<path id="moonIcon" class="hidden dark:block" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"></path>
</svg>
</button>
<button id="settingsBtn" class="p-2 border rounded dark:border-gray-700" title="Settings">
<svg class="h-5 w-5 text-gray-700 dark:text-gray-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
</svg>
</button>
</div>
</header>
<main class="max-w-7xl mx-auto p-4">
<section class="flex justify-center items-center mb-4">
<button id="prevMonthBtn" class="p-2" aria-label="Previous Month">
<svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd"
d="M12.293 2.293a1 1 0 010 1.414L6.414 9.586H18a1 1 0 110 2H6.414l5.879 5.879a1 1 0 11-1.414 1.414l-7.586-7.586a1 1 0 010-1.414l7.586-7.586a1 1 0 011.414 0z"
clip-rule="evenodd" />
</svg>
</button>
<h2 id="currentMonthYear" class="mx-4 text-xl font-semibold"></h2>
<button id="nextMonthBtn" class="p-2" aria-label="Next Month">
<svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd"
d="M7.707 17.707a1 1 0 010-1.414L13.586 11H2a1 1 0 110-2h11.586l-5.879-5.879a1 1 0 011.414-1.414l7.586 7.586a1 1 0 01-1.414 0z"
clip-rule="evenodd" />
</svg>
</button>
</section>
<section class="flex justify-between items-center mb-4">
<button id="addHabitBtn" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded">+ New Habit</button>
</section>
<div class="overflow-x-auto">
<table class="min-w-full table-border">
<thead class="bg-gray-50 dark:bg-gray-700">
<tr id="headerRow">
<th class="p-2 sticky-left" scope="col">Habits</th>
<th class="p-2 text-center" scope="col">Streak</th>
</tr>
</thead>
<tbody id="habitTableBody" class="bg-white dark:bg-gray-800"></tbody>
</table>
</div>
<!-- Stats Section -->
<div id="statsSection" class="mt-6">
<!-- Stats content will be injected here -->
</div>
</main>
<!-- Settings Modal -->
<div id="settingsModal" class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 hidden">
<div class="bg-white dark:bg-gray-800 rounded-lg w-[30rem] p-6">
<h3 class="text-lg font-semibold mb-4">Settings</h3>
<div class="space-y-4">
<button id="clearHabitsBtn" class="w-full bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded">Clear All Habits</button>
</div>
<div class="mt-6 flex justify-end">
<button id="closeSettingsBtn" class="px-4 py-2">Close</button>
</div>
</div>
</div>
<div id="habitModal" class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 hidden">
<div class="bg-white dark:bg-gray-800 rounded-lg w-[40rem] p-6">
<h3 id="modalTitle" class="text-lg font-semibold mb-4">Add New Habit</h3>
<form id="habitForm">
<div class="mb-4">
<label for="habitName" class="block mb-1">Habit Name</label>
<input type="text" id="habitName" required class="w-full px-4 py-3 border rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
</div>
<div class="mb-4">
<label for="habitType" class="block mb-1">Habit Type</label>
<select id="habitType" class="w-full px-4 py-3 border rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
<option value="default">Check/Uncheck/Fail</option>
<option value="number">Number</option>
<option value="time">Time</option>
</select>
</div>
<div id="additionalSettings"></div>
<div class="mb-4">
<label for="habitNote" class="block mb-1">Note (Optional)</label>
<textarea id="habitNote" rows="4" class="w-full px-4 py-3 border rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"></textarea>
</div>
<div class="flex justify-between">
<button type="button" id="deleteBtn" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded hidden">Delete</button>
<div class="space-x-2">
<button type="button" id="cancelBtn" class="px-4 py-2">Cancel</button>
<button type="submit" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded">Save</button>
</div>
</div>
</form>
</div>
</div>
<script>
// Initialize variables and DOM elements
let habits = JSON.parse(localStorage.getItem('habits')) || [];
let isEditing = false;
let editingHabitId = null;
let chartInstance = null;
const habitTableBody = document.getElementById('habitTableBody');
const habitModal = document.getElementById('habitModal');
const addHabitBtn = document.getElementById('addHabitBtn');
const cancelBtn = document.getElementById('cancelBtn');
const habitForm = document.getElementById('habitForm');
const modalTitle = document.getElementById('modalTitle');
const deleteBtn = document.getElementById('deleteBtn');
const darkModeToggle = document.getElementById('darkModeToggle');
const currentMonthYear = document.getElementById('currentMonthYear');
const prevMonthBtn = document.getElementById('prevMonthBtn');
const nextMonthBtn = document.getElementById('nextMonthBtn');
const clearHabitsBtn = document.getElementById('clearHabitsBtn');
const headerRow = document.getElementById('headerRow');
const currentDate = new Date();
let currentMonth = currentDate.getMonth();
let currentYear = currentDate.getFullYear();
// Utility functions
function getDaysInMonth(month, year) {
return new Date(year, month + 1, 0).getDate();
}
function getMonthName(month) {
return new Date(currentYear, month).toLocaleString('default', { month: 'long' });
}
function renderMonthYear() {
currentMonthYear.textContent = `${getMonthName(currentMonth)}, ${currentYear}`;
}
function renderDaysHeader() {
const totalDays = getDaysInMonth(currentMonth, currentYear);
while (headerRow.children.length > 2) {
headerRow.removeChild(headerRow.lastChild);
}
for (let day = 1; day <= totalDays; day++) {
const dayTh = document.createElement('th');
dayTh.className = 'p-2 text-center day-column';
dayTh.textContent = day;
dayTh.scope = 'col';
const today = new Date();
if (day === today.getDate() && currentMonth === today.getMonth() && currentYear === today.getFullYear()) {
dayTh.classList.add('today-column', 'light-bg');
}
headerRow.appendChild(dayTh);
}
}
function parseTime(timeStr) {
const [hours, minutes] = timeStr.split(':').map(Number);
if (isNaN(hours) || isNaN(minutes)) return null;
return hours * 60 + minutes; // total minutes
}
function calculateStreak(habit) {
let streak = 0;
const today = new Date();
let dateIterator = new Date(today.getFullYear(), today.getMonth(), today.getDate());
while (true) {
const monthKey = `${dateIterator.getFullYear()}-${String(dateIterator.getMonth() + 1).padStart(2, '0')}`;
const day = dateIterator.getDate();
const status = habit.history[monthKey]?.status?.[day];
let isCompleted = false;
if (habit.type === 'default' || !habit.type) {
isCompleted = status === 'completed';
} else if (habit.type === 'number') {
if (status !== undefined && habit.target !== null && !isNaN(habit.target)) {
isCompleted = status >= habit.target;
}
} else if (habit.type === 'time') {
if (status && habit.target) {
const statusTime = parseTime(status);
const targetTime = parseTime(habit.target);
if (statusTime !== null && targetTime !== null) {
const earlierIsBetter = habit.earlierIsBetter;
isCompleted = earlierIsBetter ? (statusTime <= targetTime) : (statusTime >= targetTime);
}
}
}
if (isCompleted) {
streak++;
dateIterator.setDate(dateIterator.getDate() - 1);
} else {
break;
}
}
return streak;
}
function renderHabits() {
habitTableBody.innerHTML = '';
habits.forEach(habit => {
const tr = document.createElement('tr');
tr.draggable = true;
tr.dataset.id = habit.id;
const nameTd = document.createElement('td');
nameTd.className = 'p-2 sticky-left';
const streakTd = document.createElement('td');
streakTd.className = 'p-2 text-center';
const streak = calculateStreak(habit);
streakTd.textContent = `${streak} ${streak === 1 ? 'day' : 'days'}`;
const habitContainer = document.createElement('div');
habitContainer.className = 'flex items-center justify-between';
const nameSpan = document.createElement('span');
nameSpan.className = 'habit-name';
nameSpan.title = habit.name;
nameSpan.textContent = habit.name;
const menuBtn = document.createElement('button');
menuBtn.className = 'p-1 hover:bg-gray-100 rounded dark:hover:bg-gray-700 ml-2';
menuBtn.innerHTML = `<i class="fas fa-ellipsis-v text-gray-700 dark:text-gray-200"></i>`;
menuBtn.addEventListener('click', (e) => {
e.stopPropagation();
openHabitModal(habit);
});
habitContainer.appendChild(nameSpan);
habitContainer.appendChild(menuBtn);
nameTd.appendChild(habitContainer);
tr.appendChild(nameTd);
tr.appendChild(streakTd);
const totalDays = getDaysInMonth(currentMonth, currentYear);
for (let day = 1; day <= totalDays; day++) {
const dayTd = document.createElement('td');
dayTd.className = 'p-2 text-center day-column cursor-pointer';
const today = new Date();
if (day === today.getDate() && currentMonth === today.getMonth() && currentYear === today.getFullYear()) {
dayTd.classList.add('today-column', 'light-bg');
}
const monthKey = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}`;
const status = habit.history[monthKey]?.status?.[day];
if (habit.type === 'default' || !habit.type) {
let statusHtml = '';
if (status === 'completed') {
statusHtml = '<span class="text-green-500">✓</span>';
} else if (status === 'failed') {
statusHtml = '<span class="status-failed">✗</span>';
}
dayTd.innerHTML = statusHtml;
} else if (habit.type === 'number') {
if (status !== undefined) {
const target = habit.target;
if (target !== null && !isNaN(target)) {
if (status >= target) {
dayTd.innerHTML = `<span class="text-green-500">${status}</span>`;
} else {
dayTd.innerHTML = `<span class="status-failed">${status}</span>`;
}
} else {
dayTd.textContent = status;
}
}
} else if (habit.type === 'time') {
if (status) {
const target = habit.target;
const earlierIsBetter = habit.earlierIsBetter;
if (target) {
const statusTime = parseTime(status);
const targetTime = parseTime(target);
if (statusTime !== null && targetTime !== null) {
const isGood = earlierIsBetter ? (statusTime <= targetTime) : (statusTime >= targetTime);
if (isGood) {
dayTd.innerHTML = `<span class="text-green-500">${status}</span>`;
} else {
dayTd.innerHTML = `<span class="status-failed">${status}</span>`;
}
} else {
dayTd.textContent = status;
}
} else {
dayTd.textContent = status;
}
}
}
dayTd.addEventListener('click', () => handleDayCellClick(habit, day, dayTd));
tr.appendChild(dayTd);
}
habitTableBody.appendChild(tr);
});
}
function handleDayCellClick(habit, day, td) {
const monthKey = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}`;
if (!habit.history[monthKey]) {
habit.history[monthKey] = { status: {} };
}
if (!habit.history[monthKey].status) {
habit.history[monthKey].status = {};
}
if (habit.type === 'default' || !habit.type) {
const currentStatus = habit.history[monthKey].status[day] || 'none';
let newStatus;
switch (currentStatus) {
case 'none':
newStatus = 'completed';
td.innerHTML = '<span class="text-green-500">✓</span>';
break;
case 'completed':
newStatus = 'failed';
td.innerHTML = '<span class="status-failed">✗</span>';
break;
case 'failed':
newStatus = 'none';
td.innerHTML = '';
break;
}
habit.history[monthKey].status[day] = newStatus;
saveHabits();
updateView();
} else if (habit.type === 'number') {
const currentValue = habit.history[monthKey].status[day] || '';
const inputValue = prompt('Enter value:', currentValue);
if (inputValue !== null) {
const value = parseFloat(inputValue);
if (!isNaN(value)) {
habit.history[monthKey].status[day] = value;
saveHabits();
updateView();
}
}
} else if (habit.type === 'time') {
const currentValue = habit.history[monthKey].status[day] || '';
const inputValue = prompt('Enter time (HH:MM):', currentValue);
if (inputValue !== null) {
habit.history[monthKey].status[day] = inputValue;
saveHabits();
updateView();
}
}
}
function openHabitModal(habit) {
isEditing = true;
editingHabitId = habit.id;
modalTitle.textContent = 'Edit Habit';
habitForm.reset();
document.getElementById('habitName').value = habit.name;
document.getElementById('habitType').value = habit.type || 'default';
updateAdditionalSettings();
if (habit.type === 'number') {
document.getElementById('habitTargetNumber').value = habit.target || '';
} else if (habit.type === 'time') {
document.getElementById('habitTargetTime').value = habit.target || '';
document.getElementById('habitEarlierIsBetter').value = habit.earlierIsBetter ? 'true' : 'false';
}
document.getElementById('habitNote').value = habit.note || '';
deleteBtn.classList.remove('hidden');
habitModal.classList.remove('hidden');
}
function updateAdditionalSettings() {
const habitType = document.getElementById('habitType').value;
const additionalSettings = document.getElementById('additionalSettings');
additionalSettings.innerHTML = '';
if (habitType === 'number') {
additionalSettings.innerHTML = `
<div class="mb-4">
<label for="habitTargetNumber" class="block mb-1">Target Number</label>
<input type="number" id="habitTargetNumber" step="any" class="w-full px-4 py-3 border rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
</div>
`;
} else if (habitType === 'time') {
additionalSettings.innerHTML = `
<div class="mb-4">
<label for="habitTargetTime" class="block mb-1">Target Time</label>
<input type="time" id="habitTargetTime" class="w-full px-4 py-3 border rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
</div>
<div class="mb-4">
<label for="habitEarlierIsBetter" class="block mb-1">Is Earlier Time Better?</label>
<select id="habitEarlierIsBetter" class="w-full px-4 py-3 border rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
<option value="true">Yes</option>
<option value="false">No</option>
</select>
</div>
`;
}
}
// Settings Modal
const settingsBtn = document.getElementById('settingsBtn');
const settingsModal = document.getElementById('settingsModal');
const closeSettingsBtn = document.getElementById('closeSettingsBtn');
settingsBtn.addEventListener('click', () => {
settingsModal.classList.remove('hidden');
});
closeSettingsBtn.addEventListener('click', () => {
settingsModal.classList.add('hidden');
});
// Event Listeners
addHabitBtn.addEventListener('click', () => {
isEditing = false;
editingHabitId = null;
modalTitle.textContent = 'Add New Habit';
habitForm.reset();
document.getElementById('habitType').value = 'default';
updateAdditionalSettings();
deleteBtn.classList.add('hidden');
habitModal.classList.remove('hidden');
});
cancelBtn.addEventListener('click', () => {
habitModal.classList.add('hidden');
});
// Update additional settings when habit type changes
document.getElementById('habitType').addEventListener('change', updateAdditionalSettings);
habitForm.addEventListener('submit', e => {
e.preventDefault();
const name = document.getElementById('habitName').value.trim();
const note = document.getElementById('habitNote').value.trim() || null;
const habitType = document.getElementById('habitType').value;
let target = null;
let earlierIsBetter = null;
if (habitType === 'number') {
const targetInput = document.getElementById('habitTargetNumber');
target = targetInput ? parseFloat(targetInput.value) : null;
if (isNaN(target)) target = null;
} else if (habitType === 'time') {
const targetInput = document.getElementById('habitTargetTime');
target = targetInput ? targetInput.value : null;
const earlierIsBetterInput = document.getElementById('habitEarlierIsBetter');
earlierIsBetter = earlierIsBetterInput ? earlierIsBetterInput.value === 'true' : null;
}
if (isEditing) {
const habit = habits.find(h => h.id === editingHabitId);
if (habit) {
habit.name = name;
habit.type = habitType;
habit.target = target;
habit.earlierIsBetter = earlierIsBetter;
habit.note = note;
}
} else {
habits.push({ id: Date.now().toString(), name, type: habitType, target, earlierIsBetter, note, history: {} });
}
saveHabits();
updateView();
habitModal.classList.add('hidden');
});
deleteBtn.addEventListener('click', () => {
if (confirm('Delete this habit?')) {
habits = habits.filter(h => h.id !== editingHabitId);
saveHabits();
updateView();
habitModal.classList.add('hidden');
}
});
darkModeToggle.addEventListener('click', () => {
document.documentElement.classList.toggle('dark');
localStorage.setItem('theme', document.documentElement.classList.contains('dark') ? 'dark' : 'light');
});
prevMonthBtn.addEventListener('click', () => {
if (currentMonth === 0) {
currentMonth = 11;
currentYear--;
} else {
currentMonth--;
}
updateView();
});
nextMonthBtn.addEventListener('click', () => {
if (currentMonth === 11) {
currentMonth = 0;
currentYear++;
} else {
currentMonth++;
}
updateView();
});
function exportHabits() {
const data = JSON.stringify(habits, null, 2);
const blob = new Blob([data], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `daily-habits-backup-${new Date().toISOString().split('T')[0]}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
function importHabits(file) {
const reader = new FileReader();
reader.onload = function(e) {
try {
const importedData = JSON.parse(e.target.result);
if (Array.isArray(importedData)) {
if (confirm('This will replace all existing habits. Are you sure?')) {
habits = importedData.map(habit => {
// Remove goal if present
const { goal, ...rest } = habit;
return rest;
});
saveHabits();
updateView();
alert('Habits imported successfully!');
}
} else {
alert('Invalid data format');
}
} catch (error) {
alert('Error importing data: ' + error.message);
}
};
reader.readAsText(file);
}
document.getElementById('exportHabitsBtn').addEventListener('click', exportHabits);
document.getElementById('importHabitsBtn').addEventListener('click', () => {
document.getElementById('importHabitsFile').click();
});
document.getElementById('importHabitsFile').addEventListener('change', (e) => {
if (e.target.files.length > 0) {
importHabits(e.target.files[0]);
e.target.value = '';
}
});
clearHabitsBtn.addEventListener('click', () => {
if (confirm('Are you sure you want to clear all habits? This action cannot be undone.')) {
habits = [];
saveHabits();
updateView();
}
});
function saveHabits() {
localStorage.setItem('habits', JSON.stringify(habits));
}
function updateView() {
renderMonthYear();
renderDaysHeader();
renderHabits();
renderStats();
}
// Render Stats Section
function renderStats() {
const statsSection = document.getElementById('statsSection');
const today = new Date();
const pastDate = new Date();
pastDate.setDate(today.getDate() - 30); // Last 31 days including today
const labels = [];
const data = [];
const completedToday = countCompletedTodayTasks();
const totalToday = habits.length;
for (let i = 30; i >= 0; i--) {
const date = new Date();
date.setDate(today.getDate() - i);
const month = date.getMonth() + 1;
const day = date.getDate();
labels.push(`${month}/${day}`);
let completedCount = 0;
habits.forEach(habit => {
const monthKey = `${date.getFullYear()}-${String(month).padStart(2, '0')}`;
const status = habit.history[monthKey]?.status?.[day];
let isCompleted = false;
if (habit.type === 'default' || !habit.type) {
isCompleted = status === 'completed';
} else if (habit.type === 'number') {
if (status !== undefined && habit.target !== null && !isNaN(habit.target)) {
isCompleted = status >= habit.target;
}
} else if (habit.type === 'time') {
if (status && habit.target) {
const statusTime = parseTime(status);
const targetTime = parseTime(habit.target);
if (statusTime !== null && targetTime !== null) {
const earlierIsBetter = habit.earlierIsBetter;
isCompleted = earlierIsBetter ? (statusTime <= targetTime) : (statusTime >= targetTime);
}
}
}
if (isCompleted) {
completedCount++;
}
});
data.push(completedCount);
}
const totalCompleted = data.reduce((a, b) => a + b, 0);
const averageCompleted = totalCompleted / 31 || 0;
// Calculate Best Current Streak
const maxStreak = habits.reduce((max, habit) => {
const streak = calculateStreak(habit);
return streak > max ? streak : max;
}, 0);
statsSection.innerHTML = `
<hr class="my-6 border-gray-300 dark:border-gray-600">
<div class="mt-6">
<h3 class="font-bold mb-4 text-xl">Today's Activity</h3>
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
<div class="p-4 bg-gradient-to-r from-blue-500 to-blue-600 rounded-lg shadow-lg">
<div class="text-white text-sm mb-1">Tasks Completed Today</div>
<div class="text-white text-2xl font-bold">${completedToday} / ${totalToday}</div>
</div>
<div class="p-4 bg-gradient-to-r from-purple-500 to-purple-600 rounded-lg shadow-lg">
<div class="text-white text-sm mb-1">Today's Success Rate</div>
<div class="text-white text-2xl font-bold">${totalToday > 0 ? ((completedToday / totalToday) * 100).toFixed(1) : 0}%</div>
</div>
<div class="p-4 bg-gradient-to-r from-green-500 to-green-600 rounded-lg shadow-lg">
<div class="text-white text-sm mb-1">Best Current Streak</div>
<div class="text-white text-2xl font-bold">${maxStreak} day${maxStreak !== 1 ? 's' : ''}</div>
</div>
</div>
</div>
<hr class="my-6 border-gray-300 dark:border-gray-600">
<div class="mt-6">
<h3 class="text-xl font-semibold mb-4">Progress</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<canvas id="progressChart"></canvas>
</div>
<div>
<div class="bg-white dark:bg-gray-800 p-4 rounded-lg shadow">
<h4 class="text-lg font-semibold mb-2">Statistics</h4>
<p>Total Habits: <strong>${habits.length}</strong></p>
<p>Total Completed Habits in Last 31 Days: <strong>${totalCompleted}</strong></p>
<p>Average Completed Habits per Day: <strong>${averageCompleted.toFixed(2)}</strong></p>
</div>
</div>
</div>
</div>
`;
const ctx = document.getElementById('progressChart').getContext('2d');
if (chartInstance) {
chartInstance.destroy();
}
chartInstance = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Completed Habits',
data: data,
fill: false,
borderColor: 'rgb(59, 130, 246)', // Blue color
backgroundColor: 'rgba(59, 130, 246, 0.5)',
tension: 0.1,
pointBackgroundColor: labels.map((label, index) => {
const date = new Date();
date.setDate(today.getDate() - 30 + index);
const isToday = date.toDateString() === today.toDateString();
return isToday ? 'red' : 'rgb(59, 130, 246)';
}),
pointBorderColor: labels.map((label, index) => {
const date = new Date();
date.setDate(today.getDate() - 30 + index);
const isToday = date.toDateString() === today.toDateString();
return isToday ? 'red' : 'rgb(59, 130, 246)';
}),
pointRadius: labels.map((label, index) => {
const date = new Date();
date.setDate(today.getDate() - 30 + index);
const isToday = date.toDateString() === today.toDateString();
return isToday ? 6 : 3;
}),
}]
},
options: {
responsive: true,
plugins: {
legend: {
display: false
},
tooltip: {
callbacks: {
label: function(context) {
return `Completed Habits: ${context.parsed.y}`;
}
}
}
},
scales: {
y: {
beginAtZero: true,
suggestedMax: Math.max(...data) + 1
},
x: {
ticks: {
maxTicksLimit: 10,
autoSkip: true
}
}
}
}
});
}
function countCompletedTodayTasks() {
const today = new Date();
const monthKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
let count = 0;
habits.forEach(habit => {
const status = habit.history[monthKey]?.status?.[today.getDate()];
if (habit.type === 'default' || !habit.type) {
if (status === 'completed') count++;
} else if (habit.type === 'number') {
if (status !== undefined && habit.target !== null && !isNaN(habit.target) && status >= habit.target) count++;
} else if (habit.type === 'time') {
if (status && habit.target) {
const statusTime = parseTime(status);
const targetTime = parseTime(habit.target);
if (statusTime !== null && targetTime !== null) {
const earlierIsBetter = habit.earlierIsBetter;
const isCompleted = earlierIsBetter ? (statusTime <= targetTime) : (statusTime >= targetTime);
if (isCompleted) count++;
}
}
}
});
return count;
}
window.addEventListener('DOMContentLoaded', () => {
if (localStorage.getItem('theme') === 'dark') document.documentElement.classList.add('dark');
updateView();
});
// Drag and Drop Functionality
let draggedRow = null;
habitTableBody.addEventListener('dragstart', e => {
const tr = e.target.closest('tr');
if (tr) { draggedRow = tr; tr.classList.add('dragging'); }
});
habitTableBody.addEventListener('dragend', e => {
const tr = e.target.closest('tr');
if (tr) tr.classList.remove('dragging');
Array.from(habitTableBody.children).forEach(row => {
row.classList.remove('drag-over');
});
});
habitTableBody.addEventListener('dragover', e => {
e.preventDefault();
const target = e.target.closest('tr');
if (target && target !== draggedRow) {
Array.from(habitTableBody.children).forEach(row => {
row.classList.remove('drag-over');
});
const rect = target.getBoundingClientRect();
const next = (e.clientY - rect.top) / (rect.bottom - rect.top) > 0.5;
target.classList.add('drag-over');
habitTableBody.insertBefore(draggedRow, next && target.nextSibling || target);
}
});
habitTableBody.addEventListener('drop', () => {
const ids = Array.from(habitTableBody.children).map(row => row.dataset.id);
habits.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id));
saveHabits();
updateView();
});
</script>
</body>
</html>