-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
643 lines (550 loc) · 24.1 KB
/
script.js
File metadata and controls
643 lines (550 loc) · 24.1 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
// Ebbinghaus forgetting curve intervals (in days)
const REPETITION_INTERVALS = [1, 3, 7, 14, 30];
let tasks = JSON.parse(localStorage.getItem('spacedTasks')) || [];
// Initialize on load
document.addEventListener('DOMContentLoaded', () => {
console.log('Loading tasks:', tasks.length);
updateTodayDate();
cleanupOldTasks(); // Clean up old completed tasks
// Render everything
renderTasks();
renderTodayPanel();
// Log today's tasks for debugging
const todayTasks = getTodayTasks();
console.log('Tasks due today:', todayTasks.length);
todayTasks.forEach(task => {
console.log('- ', task.text, '(Review:', getRepetitionLabel(task.repetitionIndex), ', due:', new Date(task.dueDate).toLocaleDateString() + ')');
});
// Clean up old tasks once per day (every 24 hours)
setInterval(cleanupOldTasks, 86400000);
});
function updateTodayDate() {
const todayDateElement = document.getElementById('todayDate');
const today = new Date();
const options = { weekday: 'long', month: 'long', day: 'numeric' };
todayDateElement.textContent = today.toLocaleDateString('en-US', options);
}
function isSameDay(date1, date2) {
return date1.getFullYear() === date2.getFullYear() &&
date1.getMonth() === date2.getMonth() &&
date1.getDate() === date2.getDate();
}
function getTodayTasks() {
const today = new Date();
today.setHours(0, 0, 0, 0);
return tasks.filter(task => {
// Only show study task review instances
if (!task.isStudyTask) return false;
if (!task.dueDate) return false;
const dueDate = new Date(task.dueDate);
dueDate.setHours(0, 0, 0, 0);
// Show if due today or earlier (overdue)
return dueDate <= today;
});
}
function getStudyTaskStats() {
const today = new Date();
today.setHours(0, 0, 0, 0);
// Get all study tasks scheduled for review today (due or overdue)
const tasksScheduledToday = tasks.filter(task => {
if (!task.isStudyTask || !task.dueDate) return false;
const dueDate = new Date(task.dueDate);
dueDate.setHours(0, 0, 0, 0);
// Include tasks due today or overdue
return dueDate <= today;
});
// Count how many of today's scheduled tasks are completed
const completedToday = tasksScheduledToday.filter(task => task.completed).length;
return {
total: tasksScheduledToday.length,
completed: completedToday
};
}
function renderTodayPanel() {
const todayTasksList = document.getElementById('todayTasksList');
const totalStudyTasksEl = document.getElementById('totalStudyTasks');
const completedReviewsEl = document.getElementById('completedReviews');
const progressSection = document.getElementById('progressSection');
const progressFill = document.getElementById('progressFill');
const progressText = document.getElementById('progressText');
const todayTasks = getTodayTasks();
const stats = getStudyTaskStats();
// Update stats
totalStudyTasksEl.textContent = stats.total;
completedReviewsEl.textContent = stats.completed;
// Update progress bar
if (stats.total > 0) {
const percentage = Math.round((stats.completed / stats.total) * 100);
progressSection.style.display = 'block';
progressFill.style.width = percentage + '%';
progressText.textContent = `${percentage}% complete`;
if (percentage === 100) {
progressText.textContent = '🎉 All reviews complete!';
}
} else {
progressSection.style.display = 'none';
}
console.log('📅 Today\'s reviews:', todayTasks.length, 'total (', stats.completed, 'completed,', (stats.total - stats.completed), 'remaining)');
const incompleteTasks = todayTasks.filter(t => !t.completed);
if (todayTasks.length === 0) {
todayTasksList.innerHTML = `
<div class="empty-today">
<div class="empty-today-icon">✨</div>
<p class="empty-today-text">No reviews scheduled for today.<br>Keep up the great work!</p>
</div>
`;
return;
}
if (incompleteTasks.length === 0 && todayTasks.length > 0) {
// All tasks are completed
todayTasksList.innerHTML = todayTasks.map(task => {
const reviewDate = new Date(task.dueDate);
reviewDate.setHours(0, 0, 0, 0);
const today = new Date();
today.setHours(0, 0, 0, 0);
const daysOverdue = Math.floor((today - reviewDate) / (1000 * 60 * 60 * 24));
const isOverdue = daysOverdue > 0;
let statusText = '✓ Due today';
if (isOverdue) {
statusText = daysOverdue === 1 ? '⚠️ 1 day overdue' : `⚠️ ${daysOverdue} days overdue`;
}
return `
<div class="today-task-item ${task.completed ? 'completed' : ''}">
<label class="today-task-checkbox">
<input
type="checkbox"
${task.completed ? 'checked="checked"' : ''}
onchange="toggleTask(${task.id})"
onclick="event.stopPropagation()"
>
<span class="today-checkmark"></span>
</label>
<div class="today-task-content" onclick="scrollToTask(${task.id})">
<div class="today-task-header">
<div class="today-task-text">${escapeHtml(task.text)}</div>
<span class="today-task-badge">${getRepetitionLabel(task.repetitionIndex)}</span>
</div>
<div class="today-task-time">
${statusText}
</div>
</div>
</div>
`;
}).join('');
return;
}
todayTasksList.innerHTML = todayTasks.map(task => {
const dueDate = new Date(task.dueDate);
dueDate.setHours(0, 0, 0, 0);
const today = new Date();
today.setHours(0, 0, 0, 0);
const daysOverdue = Math.floor((today - dueDate) / (1000 * 60 * 60 * 24));
const isOverdue = daysOverdue > 0;
let statusText = '✓ Due today';
if (isOverdue) {
statusText = daysOverdue === 1 ? '⚠️ 1 day overdue' : `⚠️ ${daysOverdue} days overdue`;
}
return `
<div class="today-task-item ${task.completed ? 'completed' : ''}">
<label class="today-task-checkbox">
<input
type="checkbox"
${task.completed ? 'checked="checked"' : ''}
onchange="toggleTask(${task.id})"
onclick="event.stopPropagation()"
>
<span class="today-checkmark"></span>
</label>
<div class="today-task-content" onclick="scrollToTask(${task.id})">
<div class="today-task-header">
<div class="today-task-text">${escapeHtml(task.text)}</div>
<span class="today-task-badge">${getRepetitionLabel(task.repetitionIndex)}</span>
</div>
<div class="today-task-time">
${statusText}
</div>
</div>
</div>
`;
}).join('');
}
function scrollToTask(taskId) {
const taskElements = document.querySelectorAll('.task-item');
taskElements.forEach(el => {
const checkbox = el.querySelector('input[type="checkbox"]');
if (checkbox && checkbox.onchange) {
const onchangeStr = checkbox.getAttribute('onchange');
if (onchangeStr && onchangeStr.includes(taskId.toString())) {
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
el.style.animation = 'none';
setTimeout(() => {
el.style.animation = '';
el.style.boxShadow = '0 0 0 3px rgba(193, 125, 58, 0.3)';
setTimeout(() => {
el.style.boxShadow = '';
}, 2000);
}, 10);
}
}
});
}
function manualRefresh() {
console.log('Manual refresh triggered');
const btn = document.querySelector('.refresh-btn');
btn.classList.add('spinning');
renderTasks();
renderTodayPanel();
setTimeout(() => {
btn.classList.remove('spinning');
}, 500);
}
// Helper function to reset all tasks (for debugging)
function resetAllTasks() {
if (confirm('This will uncheck all completed tasks. Continue?')) {
tasks.forEach(task => task.completed = false);
saveTasks();
renderTasks();
}
}
// Add task on Enter key
document.getElementById('taskInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') addTask();
});
function addTask() {
const input = document.getElementById('taskInput');
const isStudyTask = document.getElementById('studyTaskCheck').checked;
const taskText = input.value.trim();
if (!taskText) return;
const task = {
id: Date.now(),
text: taskText,
isStudyTask: isStudyTask,
completed: false,
createdAt: new Date().toISOString(),
repetitionIndex: 0,
dueDate: new Date().toISOString(), // Due today
isReviewInstance: isStudyTask // Study tasks are review instances from the start
};
tasks.unshift(task);
saveTasks();
renderTasks();
// Clear inputs
input.value = '';
document.getElementById('studyTaskCheck').checked = false;
input.focus();
if (isStudyTask) {
console.log(`📚 Created study task "${taskText}" - 1st Review due today`);
}
}
function cleanupOldTasks() {
const today = new Date();
today.setHours(0, 0, 0, 0);
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
// Remove completed tasks that were completed before yesterday
const initialLength = tasks.length;
tasks = tasks.filter(task => {
if (!task.completed) return true; // Keep all incomplete tasks
const completedDate = new Date(task.completedAt || task.createdAt);
completedDate.setHours(0, 0, 0, 0);
// Keep if completed today or yesterday, remove older completed tasks
return completedDate >= yesterday;
});
if (tasks.length !== initialLength) {
console.log(`Cleaned up ${initialLength - tasks.length} old completed tasks`);
saveTasks();
}
}
function toggleTask(id) {
const task = tasks.find(t => t.id === id);
if (task) {
const wasCompleted = task.completed;
task.completed = !task.completed;
if (task.completed) {
task.completedAt = new Date().toISOString();
console.log(`✓ "${task.text}" marked as complete`);
// If this is a study task and not yet mastered, schedule the next review
if (task.isStudyTask && task.repetitionIndex < REPETITION_INTERVALS.length) {
const nextIndex = task.repetitionIndex + 1;
const daysToAdd = REPETITION_INTERVALS[nextIndex];
const nextReviewDate = new Date();
nextReviewDate.setHours(0, 0, 0, 0);
nextReviewDate.setDate(nextReviewDate.getDate() + daysToAdd);
// Create the next review instance
const nextReview = {
id: Date.now() + Math.random(),
text: task.text,
isStudyTask: true,
completed: false,
createdAt: new Date().toISOString(),
repetitionIndex: nextIndex,
dueDate: nextReviewDate.toISOString(),
isReviewInstance: true,
parentTaskId: task.id
};
tasks.push(nextReview);
console.log(`📅 Next review (${getRepetitionLabel(nextIndex)}) scheduled for ${formatDate(nextReviewDate.toISOString())}`);
} else if (task.isStudyTask && task.repetitionIndex >= REPETITION_INTERVALS.length) {
console.log(`🎉 "${task.text}" mastered! All reviews completed.`);
}
} else {
delete task.completedAt;
console.log(`↩️ "${task.text}" marked as incomplete`);
// If unchecking a completed study task, remove any future reviews that were created
if (task.isStudyTask && wasCompleted && task.parentTaskId === undefined) {
// Find and remove the next review that was created when this was completed
const nextReviewIndex = task.repetitionIndex + 1;
const relatedNextReview = tasks.find(t =>
t.text === task.text &&
t.repetitionIndex === nextReviewIndex &&
t.parentTaskId === task.id &&
!t.completed
);
if (relatedNextReview) {
tasks = tasks.filter(t => t.id !== relatedNextReview.id);
console.log(`🗑️ Removed scheduled ${getRepetitionLabel(nextReviewIndex)}`);
}
}
}
saveTasks();
renderTasks();
}
}
function deleteTask(id) {
const task = tasks.find(t => t.id === id);
if (task && task.isStudyTask) {
// Find all review instances of this task (same text, not completed)
const allReviews = tasks.filter(t =>
t.text === task.text &&
t.isStudyTask &&
!t.completed
);
if (allReviews.length > 1) {
// Ask if they want to delete all future reviews too
if (confirm(`Delete all ${allReviews.length} review instances (including future) of "${task.text}"?`)) {
// Delete all reviews with this text
tasks = tasks.filter(t => !(t.text === task.text && t.isStudyTask && !t.completed));
console.log(`🗑️ Deleted all reviews for "${task.text}"`);
} else {
// Just delete this one
tasks = tasks.filter(t => t.id !== id);
console.log(`🗑️ Deleted one review instance`);
}
} else {
// Only one instance, just delete it
tasks = tasks.filter(t => t.id !== id);
}
} else {
// Regular task, just delete
tasks = tasks.filter(t => t.id !== id);
}
saveTasks();
renderTasks();
}
let editingTaskId = null;
function editTask(id) {
if (editingTaskId !== null) {
cancelEdit();
}
editingTaskId = id;
renderTasks();
}
function saveEdit(id, newText) {
const task = tasks.find(t => t.id === id);
if (task && newText.trim()) {
task.text = newText.trim();
saveTasks();
}
editingTaskId = null;
renderTasks();
}
function cancelEdit() {
editingTaskId = null;
renderTasks();
}
function clearAll() {
if (tasks.length === 0) return;
if (confirm('Are you sure you want to clear all tasks?')) {
tasks = [];
saveTasks();
renderTasks();
}
}
function saveTasks() {
localStorage.setItem('spacedTasks', JSON.stringify(tasks));
}
function formatDate(dateString) {
const date = new Date(dateString);
const now = new Date();
const diffTime = date - now;
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays === 0) return 'Today';
if (diffDays === 1) return 'Tomorrow';
if (diffDays === -1) return 'Yesterday';
if (diffDays < 0) return `${Math.abs(diffDays)} days ago`;
if (diffDays > 0) return `in ${diffDays} days`;
return date.toLocaleDateString();
}
function getRepetitionLabel(index) {
const labels = ['1st Review', '2nd Review', '3rd Review', '4th Review', '5th Review', 'Mastered'];
return labels[index] || 'Review';
}
function renderTasks() {
const tasksList = document.getElementById('tasksList');
const taskCount = document.getElementById('taskCount');
if (tasks.length === 0) {
tasksList.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">✦</div>
<p class="empty-state-text">Your tasks will appear here</p>
</div>
`;
taskCount.textContent = '0 tasks';
return;
}
// Filter tasks to show
const today = new Date();
today.setHours(0, 0, 0, 0);
const visibleTasks = tasks.filter(task => {
// Regular tasks (not study tasks) - always show if incomplete
if (!task.isStudyTask && !task.isReviewInstance) {
if (!task.completed) return true;
// Show completed regular tasks only if completed today
if (task.completedAt) {
const completedDate = new Date(task.completedAt);
completedDate.setHours(0, 0, 0, 0);
return completedDate.getTime() === today.getTime();
}
return false;
}
// Study task review instances - only show if due today or overdue
if (task.dueDate) {
const dueDate = new Date(task.dueDate);
dueDate.setHours(0, 0, 0, 0);
// Show if due today or earlier (overdue)
if (dueDate <= today) {
// If completed, only show if completed today
if (task.completed && task.completedAt) {
const completedDate = new Date(task.completedAt);
completedDate.setHours(0, 0, 0, 0);
return completedDate.getTime() === today.getTime();
}
return true;
}
}
return false;
});
if (visibleTasks.length === 0) {
tasksList.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">✨</div>
<p class="empty-state-text">No tasks for today.<br>Start fresh with a clean slate!</p>
</div>
`;
taskCount.textContent = '0 tasks';
return;
}
// Sort: incomplete first, then by due date/creation date
const sortedTasks = [...visibleTasks].sort((a, b) => {
if (a.completed !== b.completed) return a.completed ? 1 : -1;
// Sort by due date for review instances, creation date for regular tasks
const dateA = a.dueDate ? new Date(a.dueDate) : new Date(a.createdAt);
const dateB = b.dueDate ? new Date(b.dueDate) : new Date(b.createdAt);
return dateA - dateB; // Earlier dates first
});
tasksList.innerHTML = sortedTasks.map(task => {
const isEditing = editingTaskId === task.id;
// Determine what date to show
let displayDate = task.createdAt;
let dateLabel = '';
if (task.dueDate) {
const dueDate = new Date(task.dueDate);
dueDate.setHours(0, 0, 0, 0);
const diffDays = Math.floor((today - dueDate) / (1000 * 60 * 60 * 24));
if (diffDays === 0) {
dateLabel = 'Due today';
} else if (diffDays > 0) {
dateLabel = diffDays === 1 ? '1 day overdue' : `${diffDays} days overdue`;
} else {
dateLabel = formatDate(task.dueDate);
}
} else {
dateLabel = formatDate(task.createdAt);
}
return `
<div class="task-item ${task.isStudyTask ? 'study-task' : ''} ${task.completed === true ? 'completed' : ''} ${isEditing ? 'editing' : ''}"
style="animation-delay: ${visibleTasks.indexOf(task) * 0.05}s">
<label class="custom-checkbox task-checkbox">
<input
type="checkbox"
${task.completed === true ? 'checked="checked"' : ''}
onchange="toggleTask(${task.id})"
${isEditing ? 'disabled' : ''}
>
<span class="checkmark"></span>
</label>
<div class="task-content">
${isEditing ? `
<input
type="text"
class="task-edit-input"
value="${escapeHtml(task.text)}"
id="edit-input-${task.id}"
onkeypress="if(event.key === 'Enter') saveEdit(${task.id}, this.value)"
onkeydown="if(event.key === 'Escape') cancelEdit()"
autofocus
>
<div class="task-edit-actions">
<button class="btn-small btn-save" onclick="saveEdit(${task.id}, document.getElementById('edit-input-${task.id}').value)">
Save
</button>
<button class="btn-small btn-cancel" onclick="cancelEdit()">
Cancel
</button>
</div>
` : `
<div class="task-text">${escapeHtml(task.text)}</div>
<div class="task-meta">
<span class="task-date">${dateLabel}</span>
${task.isStudyTask && !task.completed ?
`<span class="repetition-info">${getRepetitionLabel(task.repetitionIndex)}</span>`
: ''}
${task.isStudyTask && task.completed ?
`<span class="repetition-info">✓ Completed</span>`
: ''}
</div>
`}
</div>
${!isEditing ? `
<div class="task-actions">
<button class="icon-btn edit" onclick="editTask(${task.id})" title="Edit task">
✎
</button>
<button class="icon-btn delete" onclick="deleteTask(${task.id})" title="Delete task">
✕
</button>
</div>
` : ''}
</div>
`}).join('');
const activeCount = visibleTasks.filter(t => !t.completed).length;
const completedCount = visibleTasks.filter(t => t.completed).length;
taskCount.textContent = `${activeCount} active${completedCount ? `, ${completedCount} completed today` : ''}`;
// Auto-focus edit input if in edit mode
if (editingTaskId !== null) {
setTimeout(() => {
const editInput = document.getElementById(`edit-input-${editingTaskId}`);
if (editInput) {
editInput.focus();
editInput.select();
}
}, 50);
}
// Update today panel
renderTodayPanel();
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}