-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtodo1.html
More file actions
999 lines (860 loc) · 39.9 KB
/
todo1.html
File metadata and controls
999 lines (860 loc) · 39.9 KB
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do Web App</title>
<style>
:root {
--background-color-light: #f4f4f4;
--text-color-light: #333;
--container-bg-light: #fff;
--input-bg-light: #fff;
--button-bg-light: #5cb85c;
--button-text-light: #fff;
--tab-bg-light: #eee;
--tab-active-bg-light: #ddd;
--task-item-bg-light: #fff;
--task-item-border-light: #ddd;
--danger-button-bg-light: #d9534f;
--background-color-dark: #333;
--text-color-dark: #f4f4f4;
--container-bg-dark: #444;
--input-bg-dark: #555;
--button-bg-dark: #6fbf73;
--button-text-dark: #333;
--tab-bg-dark: #555;
--tab-active-bg-dark: #666;
--task-item-bg-dark: #505050;
--task-item-border-dark: #666;
--danger-button-bg-dark: #e06c75;
}
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: var(--background-color-light);
color: var(--text-color-light);
transition: background-color 0.3s, color 0.3s;
}
body.dark-mode {
background-color: var(--background-color-dark);
color: var(--text-color-dark);
}
.container {
max-width: 800px;
margin: auto;
background-color: var(--container-bg-light);
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
transition: background-color 0.3s;
}
body.dark-mode .container {
background-color: var(--container-bg-dark);
}
h1 {
text-align: center;
}
.controls {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
flex-wrap: wrap;
}
.controls button,
.controls input[type="file"] {
padding: 8px 12px;
border: none;
border-radius: 4px;
cursor: pointer;
background-color: var(--button-bg-light);
color: var(--button-text-light);
font-size: 14px;
margin-top: 5px;
}
body.dark-mode .controls button,
body.dark-mode .controls input[type="file"] {
background-color: var(--button-bg-dark);
color: var(--button-text-dark);
}
.controls .danger {
background-color: var(--danger-button-bg-light);
}
body.dark-mode .controls .danger {
background-color: var(--danger-button-bg-dark);
}
.task-form {
display: flex;
flex-direction: column;
gap: 10px;
margin-bottom: 20px;
padding: 15px;
border: 1px solid var(--task-item-border-light);
border-radius: 5px;
}
body.dark-mode .task-form {
border-color: var(--task-item-border-dark);
}
.task-form input[type="text"],
.task-form input[type="date"],
.task-form select {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
background-color: var(--input-bg-light);
color: var(--text-color-light);
}
body.dark-mode .task-form input[type="text"],
body.dark-mode .task-form input[type="date"],
body.dark-mode .task-form select {
background-color: var(--input-bg-dark);
color: var(--text-color-dark);
border-color: #666;
}
.task-form button {
padding: 10px 15px;
background-color: var(--button-bg-light);
color: var(--button-text-light);
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
body.dark-mode .task-form button {
background-color: var(--button-bg-dark);
color: var(--button-text-dark);
}
.tabs {
display: flex;
margin-bottom: 10px;
overflow-x: auto;
/* For many months */
padding-bottom: 5px;
/* Space for scrollbar */
}
.tab-button {
padding: 10px 15px;
cursor: pointer;
border: none;
background-color: var(--tab-bg-light);
margin-right: 5px;
border-radius: 4px 4px 0 0;
font-size: 14px;
white-space: nowrap;
}
body.dark-mode .tab-button {
background-color: var(--tab-bg-dark);
color: var(--text-color-dark);
}
.tab-button.active {
background-color: var(--tab-active-bg-light);
font-weight: bold;
}
body.dark-mode .tab-button.active {
background-color: var(--tab-active-bg-dark);
}
.task-list {
list-style-type: none;
padding: 0;
}
.task-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px;
border: 1px solid var(--task-item-border-light);
margin-bottom: 8px;
border-radius: 4px;
background-color: var(--task-item-bg-light);
transition: background-color 0.3s;
}
body.dark-mode .task-item {
background-color: var(--task-item-bg-dark);
border-color: var(--task-item-border-dark);
}
.task-item.completed span {
text-decoration: line-through;
color: #888;
}
body.dark-mode .task-item.completed span {
color: #aaa;
}
.task-item span {
flex-grow: 1;
margin-right: 10px;
}
.task-item .due-date {
font-size: 0.9em;
color: #666;
margin-right: 10px;
}
body.dark-mode .task-item .due-date {
color: #ccc;
}
.task-item button {
padding: 6px 10px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
margin-left: 5px;
}
.task-item .complete-btn {
background-color: #5cb85c;
color: white;
}
body.dark-mode .task-item .complete-btn {
background-color: #6fbf73;
color: #333;
}
.task-item .delete-btn {
background-color: var(--danger-button-bg-light);
color: white;
}
body.dark-mode .task-item .delete-btn {
background-color: var(--danger-button-bg-dark);
}
/* Responsive adjustments */
@media (max-width: 600px) {
.controls {
flex-direction: column;
align-items: stretch;
}
.controls button,
.controls input[type="file"] {
width: 100%;
margin-bottom: 5px;
}
.task-form {
padding: 10px;
}
.tabs {
font-size: 12px;
/* Smaller tabs on mobile */
}
.tab-button {
padding: 8px 10px;
}
.task-item {
flex-direction: column;
align-items: flex-start;
}
.task-item div:first-child {
/* Task text and due date container */
margin-bottom: 8px;
width: 100%;
}
.task-item .actions {
width: 100%;
display: flex;
justify-content: flex-end;
}
.task-item .actions button {
flex-grow: 1;
margin-left: 5px;
}
.task-item .actions button:first-child {
margin-left: 0;
}
}
</style>
</head>
<body>
<div class="container">
<h1>My To-Do List</h1>
<div class="controls">
<button id="toggleModeBtn">Toggle Light/Dark Mode</button>
<button id="exportDataBtn">Export Data (JSON)</button>
<div>
<label for="importDataFile" style="font-size: 12px; margin-right: 5px;">Import Data (JSON):</label>
<input type="file" id="importDataFile" accept=".json" style="padding: 3px; font-size: 12px;">
</div>
</div>
<form id="taskForm" class="task-form">
<input type="text" id="taskInput" placeholder="Enter task description..." required>
<input type="date" id="taskDueDate" required>
<select id="taskRecurrence">
<option value="none">No Recurrence</option>
<option value="daily">Daily</option>
<option value="weekly">Weekly</option>
<option value="monthly">Monthly</option>
<!-- <option value="yearly">Yearly</option> -->
</select>
<button type="submit">Add Task</button>
</form>
<div class="tabs" id="monthTabs">
<!-- Tabs will be generated here -->
</div>
<ul id="taskList" class="task-list">
<!-- Tasks will be listed here -->
</ul>
</div>
<script>
const taskForm = document.getElementById('taskForm');
const taskInput = document.getElementById('taskInput');
const taskDueDate = document.getElementById('taskDueDate');
const taskRecurrence = document.getElementById('taskRecurrence');
const taskList = document.getElementById('taskList');
const monthTabsContainer = document.getElementById('monthTabs');
const toggleModeBtn = document.getElementById('toggleModeBtn');
const exportDataBtn = document.getElementById('exportDataBtn');
const importDataFile = document.getElementById('importDataFile');
let tasks = [];
let currentMonthYear = ''; // To store the currently selected tab, e.g., "2025-05"
// --- Local Storage ---
function saveTasks() {
localStorage.setItem('tasks', JSON.stringify(tasks));
}
function loadTasks() {
const storedTasks = localStorage.getItem('tasks');
if (storedTasks) {
tasks = JSON.parse(storedTasks).map(task => ({
...task,
completedInstances: task.completedInstances || [], // Ensure array exists
deletedInstances: task.deletedInstances || [] // Ensure array exists
}));
}
}
function saveThemePreference(theme) {
localStorage.setItem('theme', theme);
}
function loadThemePreference() {
const theme = localStorage.getItem('theme');
if (theme === 'dark') {
document.body.classList.add('dark-mode');
} else {
document.body.classList.remove('dark-mode');
}
}
// --- Task Management ---
function addTask(text, dueDate, recurrence, completed = false, id = Date.now().toString()) {
const task = {
id,
text,
dueDate, // This is the first due date
recurrence,
completed, // For the first instance or if the whole series is conceptually done
originalDueDate: dueDate, // The very first date, used as anchor for recurrence
completedInstances: [], // Dates of completed recurring instances
deletedInstances: [] // Dates of "deleted" (skipped) recurring instances
};
tasks.push(task);
saveTasks();
renderApp();
}
// Toggles completion for the MAIN task item (original due date)
function toggleMainTaskComplete(taskId) {
tasks = tasks.map(task =>
task.id === taskId ? {
...task,
completed: !task.completed
} : task
);
saveTasks();
renderTasksForCurrentMonth();
}
// Deletes the ENTIRE task series (original and all recurrences)
function deleteTaskSeries(taskId) {
tasks = tasks.filter(task => task.id !== taskId);
saveTasks();
renderApp(); // Re-render app as task deletion might affect month tabs
}
// Marks a specific recurring instance as complete or not
function toggleCompleteInstance(originalTaskId, instanceDate) {
tasks = tasks.map(task => {
if (task.id === originalTaskId) {
const completedInstances = task.completedInstances || [];
if (completedInstances.includes(instanceDate)) {
// Already completed, so un-complete it
return {
...task,
completedInstances: completedInstances.filter(d => d !== instanceDate)
};
} else {
// Not completed, so complete it
return {
...task,
completedInstances: [...completedInstances, instanceDate]
};
}
}
return task;
});
saveTasks();
renderTasksForCurrentMonth();
}
// "Deletes" (skips) a specific recurring instance
function deleteInstance(originalTaskId, instanceDate) {
tasks = tasks.map(task => {
if (task.id === originalTaskId) {
const deletedInstances = task.deletedInstances || [];
if (!deletedInstances.includes(instanceDate)) { // Avoid duplicates
return {
...task,
deletedInstances: [...deletedInstances, instanceDate]
};
}
}
return task;
});
saveTasks();
renderTasksForCurrentMonth(); // Could also call renderApp if many deletions affect tabs
}
// --- Recurrence Logic ---
function getNextDueDate(currentDueDate, recurrence) {
const date = new Date(currentDueDate + 'T00:00:00'); // Ensure parsing as local time
if (isNaN(date.getTime())) { // Invalid date check
console.error("Invalid date in getNextDueDate:", currentDueDate);
return null;
}
switch (recurrence) {
case 'daily':
date.setDate(date.getDate() + 1);
break;
case 'weekly':
date.setDate(date.getDate() + 7);
break;
case 'monthly':
date.setMonth(date.getMonth() + 1);
break;
default:
return null;
}
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
// --- Rendering ---
function renderTasksForCurrentMonth() {
taskList.innerHTML = '';
if (!currentMonthYear) return;
const [year, month] = currentMonthYear.split('-').map(Number);
const tasksToDisplayIntermediate = tasks.flatMap(originalTask => {
const taskInstances = [];
const originalTaskDateObj = new Date(originalTask.dueDate + 'T00:00:00');
// 1. Handle the original task instance
if (originalTaskDateObj.getFullYear() === year && (originalTaskDateObj.getMonth() + 1) ===
month) {
if (!originalTask.deletedInstances.includes(originalTask.dueDate)) {
taskInstances.push({
...originalTask,
displayDate: originalTask.dueDate,
isRecurringInstance: false,
isInstanceCompleted: originalTask.completed,
});
}
}
// 2. Generate and handle recurring instances
if (originalTask.recurrence !== 'none') {
let baseDateForNext = originalTask.originalDueDate;
const maxRecurrences = 365;
let count = 0;
while (count < maxRecurrences) {
const currentInstanceDate = getNextDueDate(baseDateForNext, originalTask.recurrence);
if (!currentInstanceDate) break;
baseDateForNext = currentInstanceDate;
const recurringTaskDateObj = new Date(currentInstanceDate + 'T00:00:00');
if (isNaN(recurringTaskDateObj.getTime())) break;
const recurringTaskYear = recurringTaskDateObj.getFullYear();
const recurringTaskMonth = recurringTaskDateObj.getMonth() + 1;
if (recurringTaskYear > year + 1 || (recurringTaskYear === year + 1 &&
recurringTaskMonth > month)) {
break;
}
if (recurringTaskYear === year && recurringTaskMonth === month) {
if (!originalTask.deletedInstances.includes(currentInstanceDate)) {
const isInstanceCompleted = originalTask.completedInstances.includes(
currentInstanceDate);
taskInstances.push({
...originalTask,
id: originalTask.id,
instanceDateId: `${originalTask.id}-recur-${currentInstanceDate}`,
displayDate: currentInstanceDate,
isRecurringInstance: true,
isInstanceCompleted: isInstanceCompleted
});
}
}
count++;
}
}
return taskInstances;
});
tasksToDisplayIntermediate.sort((a, b) => new Date(a.displayDate) - new Date(b.displayDate));
const uniqueTasksToDisplay = [];
const seenKeys = new Set();
for (const task of tasksToDisplayIntermediate) {
let key;
if (task.isRecurringInstance) {
key = task.instanceDateId;
} else {
key = `original-${task.id}-${task.displayDate}`;
}
if (!seenKeys.has(key)) {
uniqueTasksToDisplay.push(task);
seenKeys.add(key);
}
}
if (uniqueTasksToDisplay.length === 0) {
taskList.innerHTML = '<li>No tasks for this month.</li>';
if (document.body.classList.contains('dark-mode')) {
taskList.firstChild.style.color = 'var(--text-color-dark)';
} else {
taskList.firstChild.style.color = 'var(--text-color-light)';
}
return;
}
uniqueTasksToDisplay.forEach(task => {
const li = document.createElement('li');
li.className = 'task-item';
li.id = task.isRecurringInstance ? task.instanceDateId : `task-${task.id}-${task.displayDate}`;
if (task.isInstanceCompleted) {
li.classList.add('completed');
}
const taskTextSpan = document.createElement('span');
taskTextSpan.textContent = task.text;
const dueDateSpan = document.createElement('span');
dueDateSpan.className = 'due-date';
dueDateSpan.textContent = `Due: ${task.displayDate}`;
if (task.isRecurringInstance) {
dueDateSpan.textContent += " (Recurring)";
}
const textAndDateDiv = document.createElement('div');
textAndDateDiv.appendChild(taskTextSpan);
textAndDateDiv.appendChild(dueDateSpan);
const actionsDiv = document.createElement('div');
actionsDiv.className = 'actions';
if (task.isRecurringInstance) {
const completeInstanceBtn = document.createElement('button');
completeInstanceBtn.className = 'complete-btn';
completeInstanceBtn.textContent = task.isInstanceCompleted ? 'Undo' : 'Complete';
completeInstanceBtn.onclick = () => toggleCompleteInstance(task.id, task
.displayDate); // task.id is originalTaskId
actionsDiv.appendChild(completeInstanceBtn);
const deleteInstanceBtn = document.createElement('button');
deleteInstanceBtn.className = 'delete-btn'; // Standard delete button style
deleteInstanceBtn.textContent = 'Skip Instance';
deleteInstanceBtn.onclick = () => deleteInstance(task.id, task
.displayDate); // task.id is originalTaskId
actionsDiv.appendChild(deleteInstanceBtn);
// --- Add Delete Series Button for Recurring Instances ---
const deleteSeriesBtnInstance = document.createElement('button');
deleteSeriesBtnInstance.className =
'delete-btn'; // Use same styling as other delete buttons
deleteSeriesBtnInstance.style.marginLeft = '5px'; // Add a little space
deleteSeriesBtnInstance.textContent = 'Delete Series';
deleteSeriesBtnInstance.onclick = () => {
if (confirm(
`Are you sure you want to delete the entire series for "${task.text}"?`)) {
deleteTaskSeries(task.id); // task.id is the originalTaskId
}
};
actionsDiv.appendChild(deleteSeriesBtnInstance);
// --- End of new button ---
} else { // Original task item (non-recurring, or the anchor of a series)
const completeBtn = document.createElement('button');
completeBtn.className = 'complete-btn';
completeBtn.textContent = task.completed ? 'Undo' : 'Complete';
completeBtn.onclick = () => toggleMainTaskComplete(task.id);
actionsDiv.appendChild(completeBtn);
const deleteBtn = document.createElement('button');
deleteBtn.className = 'delete-btn';
deleteBtn.textContent = 'Delete Series'; // Or just "Delete" if it's not a series anchor
if (task.recurrence === 'none') {
deleteBtn.textContent = 'Delete Task';
}
deleteBtn.onclick = () => {
const confirmMsg = task.recurrence !== 'none' ?
`Are you sure you want to delete the entire series for "${task.text}"?` :
`Are you sure you want to delete the task "${task.text}"?`;
if (confirm(confirmMsg)) {
deleteTaskSeries(task.id); // deleteTaskSeries handles both single and series
}
};
actionsDiv.appendChild(deleteBtn);
}
li.appendChild(textAndDateDiv);
li.appendChild(actionsDiv);
taskList.appendChild(li);
});
}
function renderMonthTabs() {
monthTabsContainer.innerHTML = '';
const uniqueMonths = new Set();
const todayForTabs = new Date();
const currentYear = todayForTabs.getFullYear();
const currentMonth = todayForTabs.getMonth() + 1; // 1-indexed month
const currentMonthStr = `${currentYear}-${String(currentMonth).padStart(2, '0')}`;
const oneMonthAgoDate = new Date(todayForTabs);
oneMonthAgoDate.setMonth(todayForTabs.getMonth() - 1);
const oneMonthAgoYear = oneMonthAgoDate.getFullYear();
const oneMonthAgoMonth = oneMonthAgoDate.getMonth() + 1;
const oneMonthAgoStr = `${oneMonthAgoYear}-${String(oneMonthAgoMonth).padStart(2, '0')}`;
// Add "one month ago" and "current month" by default
uniqueMonths.add(oneMonthAgoStr);
uniqueMonths.add(currentMonthStr);
// Add next 11 future months by default (total 12 including current, effectively 13 with past one)
for (let i = 1; i <= 11; i++) { // Start from 1 to get future months relative to current
const date = new Date(currentYear, (currentMonth - 1) + i,
1); // Month is 0-indexed for Date constructor
const yearToAdd = date.getFullYear();
const monthToAdd = date.getMonth() + 1;
uniqueMonths.add(`${yearToAdd}-${String(monthToAdd).padStart(2, '0')}`);
}
tasks.forEach(task => {
// Add month of original due date, if within the allowed range (one month ago to future)
const originalTaskDateObj = new Date(task.originalDueDate + 'T00:00:00');
if (!isNaN(originalTaskDateObj.getTime())) {
const taskYear = originalTaskDateObj.getFullYear();
const taskMonth = originalTaskDateObj.getMonth() + 1;
const taskMonthStr = `${taskYear}-${String(taskMonth).padStart(2, '0')}`;
if (taskMonthStr >= oneMonthAgoStr) {
uniqueMonths.add(taskMonthStr);
}
}
// Add months for active recurring tasks, if within the allowed range
if (task.recurrence !== 'none') {
let currentDate = task.originalDueDate;
// Project tabs for a reasonable future period (e.g., 2 years from today)
const futureLimitDate = new Date(currentYear + 2, currentMonth - 1, todayForTabs.getDate());
for (let i = 0; i < 730; i++) { // Limit iterations
currentDate = getNextDueDate(currentDate, task.recurrence);
if (!currentDate) break;
const recurringDateObj = new Date(currentDate + 'T00:00:00');
if (isNaN(recurringDateObj.getTime()) || recurringDateObj > futureLimitDate) break;
const recurringTaskYear = recurringDateObj.getFullYear();
const recurringTaskMonth = recurringDateObj.getMonth() + 1;
const recurringMonthStr =
`${recurringTaskYear}-${String(recurringTaskMonth).padStart(2, '0')}`;
if (!task.deletedInstances.includes(currentDate) && recurringMonthStr >=
oneMonthAgoStr) {
uniqueMonths.add(recurringMonthStr);
}
}
}
});
// Filter out any months older than "one month ago" that might have slipped through
const validDisplayMonths = Array.from(uniqueMonths).filter(monthYearStr => {
return monthYearStr >= oneMonthAgoStr; // String comparison works for "YYYY-MM"
});
const sortedMonths = validDisplayMonths.sort();
let newCurrentMonthYear = currentMonthYear; // Preserve current selection if still valid
// Determine the active tab
if (sortedMonths.length > 0) {
// Check if the globally stored currentMonthYear is valid under new rules
const [selectedYear, selectedMonth] = currentMonthYear ? currentMonthYear.split('-').map(Number) : [0,
0
];
const currentMonthYearIsValid = currentMonthYear &&
sortedMonths.includes(currentMonthYear) &&
currentMonthYear >= oneMonthAgoStr;
if (currentMonthYearIsValid) {
newCurrentMonthYear = currentMonthYear; // Keep it
} else if (sortedMonths.includes(currentMonthStr)) { // Default to current actual month if available
newCurrentMonthYear = currentMonthStr;
} else if (sortedMonths.includes(oneMonthAgoStr) && currentMonthStr < oneMonthAgoStr) {
// This case is unlikely if currentMonthStr is always added, but as a fallback
newCurrentMonthYear = oneMonthAgoStr;
} else { // Otherwise, default to the first month in the sorted list
newCurrentMonthYear = sortedMonths[0];
}
} else {
// Should not happen as we add current and one month ago by default
newCurrentMonthYear = currentMonthStr;
if (!monthTabsContainer.querySelector(`[data-month-year="${newCurrentMonthYear}"]`)) {
uniqueMonths.add(newCurrentMonthYear); // Ensure it's in the set
// Re-sort and add if it was somehow missed (defensive)
const tempSorted = Array.from(uniqueMonths).filter(m => m >= oneMonthAgoStr).sort();
if (tempSorted.length > 0) newCurrentMonthYear = tempSorted[0];
}
}
currentMonthYear = newCurrentMonthYear; // Update global currentMonthYear
sortedMonths.forEach(monthYearStr => {
const tabButton = document.createElement('button');
tabButton.className = 'tab-button';
tabButton.textContent = monthYearStr;
tabButton.dataset.monthYear = monthYearStr;
if (monthYearStr === currentMonthYear) {
tabButton.classList.add('active');
}
tabButton.onclick = () => {
const [clickedYear, clickedMonth] = monthYearStr.split('-').map(Number);
const nowForClick = new Date();
const cYear = nowForClick.getFullYear();
const cMonth = nowForClick.getMonth() + 1;
const oneMonthAgoClick = new Date(nowForClick);
oneMonthAgoClick.setMonth(nowForClick.getMonth() - 1);
const omacYear = oneMonthAgoClick.getFullYear();
const omacMonth = oneMonthAgoClick.getMonth() + 1;
// Check if the clicked tab is still valid (not older than one month ago due to date change)
if (clickedYear < omacYear || (clickedYear === omacYear && clickedMonth < omacMonth)) {
renderApp(); // Re-render tabs to correct the view
return;
}
currentMonthYear = monthYearStr;
document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
tabButton.classList.add('active');
renderTasksForCurrentMonth();
};
monthTabsContainer.appendChild(tabButton);
});
// Final check for active tab
const activeTab = monthTabsContainer.querySelector('.tab-button.active');
if (!activeTab && monthTabsContainer.firstChild && monthTabsContainer.firstChild.classList.contains(
'tab-button')) {
monthTabsContainer.firstChild.classList.add('active');
currentMonthYear = monthTabsContainer.firstChild.dataset.monthYear;
} else if (!monthTabsContainer.firstChild) { // No tabs at all
currentMonthYear = currentMonthStr; // Fallback
// Optionally, create a default tab for current month if none rendered
const tabButton = document.createElement('button');
tabButton.className = 'tab-button active';
tabButton.textContent = currentMonthStr;
tabButton.dataset.monthYear = currentMonthStr;
monthTabsContainer.appendChild(tabButton);
}
}
function renderApp() {
renderMonthTabs();
renderTasksForCurrentMonth();
}
// --- Event Listeners ---
taskForm.addEventListener('submit', (e) => {
e.preventDefault();
const text = taskInput.value.trim();
const dueDate = taskDueDate.value;
const recurrence = taskRecurrence.value;
if (text && dueDate) {
addTask(text, dueDate, recurrence);
taskInput.value = '';
// taskDueDate.value = ''; // Keep date for easier subsequent entries or reset as preferred
// taskRecurrence.value = 'none';
} else {
alert('Please enter task description and due date.');
}
});
toggleModeBtn.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
saveThemePreference(document.body.classList.contains('dark-mode') ? 'dark' : 'light');
});
exportDataBtn.addEventListener('click', () => {
if (tasks.length === 0) {
alert("No data to export.");
return;
}
const jsonData = JSON.stringify(tasks, null, 2);
const blob = new Blob([jsonData], {
type: 'application/json'
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'todo-data.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
importDataFile.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
try {
const importedTasksRaw = JSON.parse(e.target.result);
if (Array.isArray(importedTasksRaw)) {
// Validate and ensure new fields exist
const importedTasks = importedTasksRaw.map(task => ({
id: task.id || Date.now().toString() + Math
.random(), // Ensure ID
text: task.text || "",
dueDate: task.dueDate,
recurrence: task.recurrence || "none",
completed: task.completed || false,
originalDueDate: task.originalDueDate || task.dueDate,
completedInstances: Array.isArray(task.completedInstances) ?
task.completedInstances : [],
deletedInstances: Array.isArray(task.deletedInstances) ? task
.deletedInstances : []
}));
// More robust validation could be added here
const isValid = importedTasks.every(task =>
task.hasOwnProperty('id') &&
task.hasOwnProperty('text') &&
task.hasOwnProperty('dueDate') &&
// Check for valid date format if necessary
task.hasOwnProperty('recurrence') &&
task.hasOwnProperty('completed') &&
task.hasOwnProperty('originalDueDate') &&
task.hasOwnProperty('completedInstances') &&
task.hasOwnProperty('deletedInstances')
);
if (isValid) {
if (confirm("Importing will replace all current tasks. Continue?")) {
tasks = importedTasks;
saveTasks();
if (tasks.length > 0 && tasks[0].dueDate) {
const firstTaskDate = new Date(tasks[0].dueDate + 'T00:00:00');
currentMonthYear =
`${firstTaskDate.getFullYear()}-${String(firstTaskDate.getMonth() + 1).padStart(2, '0')}`;
} else {
const today = new Date();
currentMonthYear =
`${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
}
renderApp();
alert("Data imported successfully!");
}
} else {
alert(
"Invalid JSON file format or missing task properties after processing."
);
}
} else {
alert("Invalid JSON file format. Expected an array of tasks.");
}
} catch (error) {
console.error("Import error:", error);
alert("Error reading or parsing JSON file: " + error.message);
} finally {
importDataFile.value = '';
}
};
reader.readAsText(file);
}
});
loadThemePreference();
loadTasks();
const today = new Date();
const yyyy = today.getFullYear();
const mm = String(today.getMonth() + 1).padStart(2, '0'); // Current month (1-indexed)
const dd = String(today.getDate()).padStart(2, '0');
const oneMonthAgoInitial = new Date(today);
oneMonthAgoInitial.setMonth(today.getMonth() - 1);
const oneMonthAgoInitialYear = oneMonthAgoInitial.getFullYear();
const oneMonthAgoInitialMonth = oneMonthAgoInitial.getMonth() + 1;
if (!taskDueDate.value) {
taskDueDate.value = `${yyyy}-${mm}-${dd}`;
}
// Set initial currentMonthYear for tab selection
const currentActualMonthForLoad = `${yyyy}-${mm}`;
let validInitialCurrentMonthYear = false;
if (currentMonthYear) {
const [selectedYear, selectedMonth] = currentMonthYear.split('-').map(Number);
if (selectedYear > oneMonthAgoInitialYear ||
(selectedYear === oneMonthAgoInitialYear && selectedMonth >= oneMonthAgoInitialMonth)) {
validInitialCurrentMonthYear = true; // Loaded currentMonthYear is within allowed range
}
}
if (!validInitialCurrentMonthYear) { // If not valid or not set
currentMonthYear = currentActualMonthForLoad; // Default to current actual month
}
// renderMonthTabs will further refine this based on available tabs.
renderApp();
</script>
</body>
</html>