-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
715 lines (616 loc) · 26.6 KB
/
script.js
File metadata and controls
715 lines (616 loc) · 26.6 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
document.addEventListener('DOMContentLoaded', function() {
// DOM Elements
const authContainer = document.getElementById('auth-container');
const appContainer = document.getElementById('app-container');
const loginForm = document.getElementById('login-form');
const signupForm = document.getElementById('signup-form');
const loginTab = document.getElementById('login-tab');
const signupTab = document.getElementById('signup-tab');
const logoutBtn = document.getElementById('logout-btn');
const usernameDisplay = document.getElementById('username-display');
const profileIcon = document.getElementById('profile-icon');
const themeToggle = document.getElementById('theme-toggle');
const taskInput = document.getElementById('task-input');
const addTaskBtn = document.getElementById('add-task-btn');
const taskList = document.getElementById('task-list');
const taskListTitle = document.getElementById('task-list-title');
const prioritySelect = document.getElementById('priority');
const categorySelect = document.getElementById('category');
const customCategoryInput = document.getElementById('custom-category');
const dueDateInput = document.getElementById('due-date');
const taskSearch = document.getElementById('task-search');
const sortBySelect = document.getElementById('sort-by');
const totalTasksSpan = document.getElementById('total-tasks');
const completedTasksSpan = document.getElementById('completed-tasks');
const pendingTasksSpan = document.getElementById('pending-tasks');
const progressCircle = document.querySelector('.circle-fill');
const progressPercentage = document.querySelector('.percentage');
const editTaskModal = document.getElementById('edit-task-modal');
const editTaskForm = document.getElementById('edit-task-form');
const editTaskText = document.getElementById('edit-task-text');
const editPriority = document.getElementById('edit-priority');
const editCategory = document.getElementById('edit-category');
const editDueDate = document.getElementById('edit-due-date');
const closeModal = document.querySelector('.close-modal');
// Sidebar elements
const viewButtons = document.querySelectorAll('.sidebar-menu button');
const categoryItems = document.querySelectorAll('.category-item');
// State variables
let currentUser = null;
let tasks = [];
let currentView = 'all';
let currentCategory = 'all';
let currentEditTaskId = null;
let draggedItem = null;
// Initialize the app
init();
function init() {
loadThemePreference();
setupEventListeners();
checkAuthState();
// Check for expired tasks daily
setInterval(checkForExpiredTasks, 86400000);
// Check for reminders every minute
setInterval(checkForReminders, 60000);
}
function setupEventListeners() {
// Auth related
loginTab.addEventListener('click', () => switchAuthTab('login'));
signupTab.addEventListener('click', () => switchAuthTab('signup'));
loginForm.addEventListener('submit', handleLogin);
signupForm.addEventListener('submit', handleSignup);
logoutBtn.addEventListener('click', handleLogout);
// Theme toggle
themeToggle.addEventListener('change', toggleTheme);
// Task related
addTaskBtn.addEventListener('click', addTask);
taskInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') addTask();
});
// Category selector
categorySelect.addEventListener('change', function() {
if (this.value === 'other') {
customCategoryInput.style.display = 'block';
} else {
customCategoryInput.style.display = 'none';
}
});
// View and category filters
viewButtons.forEach(button => {
button.addEventListener('click', () => {
currentView = button.getAttribute('data-view');
updateActiveViewButton();
filterAndRenderTasks();
});
});
categoryItems.forEach(item => {
item.addEventListener('click', () => {
currentCategory = item.getAttribute('data-category');
updateActiveCategoryItem();
filterAndRenderTasks();
});
});
// Search and sort
taskSearch.addEventListener('input', filterAndRenderTasks);
sortBySelect.addEventListener('change', filterAndRenderTasks);
// Edit task modal
closeModal.addEventListener('click', () => {
editTaskModal.style.display = 'none';
});
editTaskForm.addEventListener('submit', saveEditedTask);
// Drag and drop
taskList.addEventListener('dragstart', handleDragStart);
taskList.addEventListener('dragover', handleDragOver);
taskList.addEventListener('dragleave', handleDragLeave);
taskList.addEventListener('drop', handleDrop);
taskList.addEventListener('dragend', handleDragEnd);
// Click outside modal to close
window.addEventListener('click', (e) => {
if (e.target === editTaskModal) {
editTaskModal.style.display = 'none';
}
});
}
function checkAuthState() {
const user = fetchFromDummyExcel().find(u => u.id === localStorage.getItem('currentUserId'));
if (user) {
currentUser = user;
usernameDisplay.textContent = user.name;
setProfileIcon(user.gender);
authContainer.style.display = 'none';
appContainer.style.display = 'flex';
loadTasks();
} else {
authContainer.style.display = 'flex';
appContainer.style.display = 'none';
}
}
function switchAuthTab(tab) {
if (tab === 'login') {
loginForm.style.display = 'block';
signupForm.style.display = 'none';
loginTab.classList.add('active');
signupTab.classList.remove('active');
} else {
loginForm.style.display = 'none';
signupForm.style.display = 'block';
loginTab.classList.remove('active');
signupTab.classList.add('active');
}
}
function handleLogin(e) {
e.preventDefault();
const email = document.getElementById('login-email').value;
const password = document.getElementById('login-password').value;
// Simple validation
if (!email || !password) {
alert('Please fill in all fields');
return;
}
// Fetch from dummy Excel
const users = fetchFromDummyExcel();
const user = users.find(u => u.email === email && u.password === password);
if (user) {
currentUser = user;
localStorage.setItem('currentUserId', user.id);
usernameDisplay.textContent = user.name;
setProfileIcon(user.gender);
authContainer.style.display = 'none';
appContainer.style.display = 'flex';
loadTasks();
} else {
alert('Invalid email or password');
}
}
function handleSignup(e) {
e.preventDefault();
const name = document.getElementById('signup-name').value;
const email = document.getElementById('signup-email').value;
const password = document.getElementById('signup-password').value;
const confirmPassword = document.getElementById('signup-confirm-password').value;
const gender = document.getElementById('signup-gender').value;
// Validation
if (!name || !email || !password || !confirmPassword) {
alert('Please fill in all fields');
return;
}
if (password !== confirmPassword) {
alert('Passwords do not match');
return;
}
// Check if user already exists
const users = fetchFromDummyExcel();
const userExists = users.some(u => u.email === email);
if (userExists) {
alert('User with this email already exists');
return;
}
// Create new user
const newUser = {
id: Date.now().toString(),
name,
email,
password,
gender,
createdAt: new Date().toISOString()
};
// Save to dummy Excel
saveToDummyExcel(newUser);
// Log in the new user
currentUser = newUser;
localStorage.setItem('currentUserId', newUser.id);
usernameDisplay.textContent = newUser.name;
setProfileIcon(newUser.gender);
authContainer.style.display = 'none';
appContainer.style.display = 'flex';
// Clear form
document.getElementById('signup-name').value = '';
document.getElementById('signup-email').value = '';
document.getElementById('signup-password').value = '';
document.getElementById('signup-confirm-password').value = '';
// Switch to login tab for next time
switchAuthTab('login');
}
function handleLogout() {
currentUser = null;
localStorage.removeItem('currentUserId');
authContainer.style.display = 'flex';
appContainer.style.display = 'none';
tasks = [];
renderTasks();
}
// Simulated Excel functions
function saveToDummyExcel(user) {
const excelData = JSON.parse(localStorage.getItem('excelData')) || [];
const existingIndex = excelData.findIndex(u => u.id === user.id);
if (existingIndex >= 0) {
excelData[existingIndex] = user;
} else {
excelData.push(user);
}
localStorage.setItem('excelData', JSON.stringify(excelData));
}
function fetchFromDummyExcel() {
return JSON.parse(localStorage.getItem('excelData')) || [];
}
// Profile icon function
function setProfileIcon(gender) {
let iconClass = 'fas fa-user'; // Default
switch(gender) {
case 'male':
iconClass = 'fas fa-male';
break;
case 'female':
iconClass = 'fas fa-female';
break;
default:
iconClass = 'fas fa-user-astronaut'; // For others
}
profileIcon.className = iconClass;
}
function loadThemePreference() {
const isDarkMode = localStorage.getItem('darkMode') === 'true';
themeToggle.checked = isDarkMode;
document.body.classList.toggle('dark-mode', isDarkMode);
}
function toggleTheme() {
const isDarkMode = themeToggle.checked;
document.body.classList.toggle('dark-mode', isDarkMode);
localStorage.setItem('darkMode', isDarkMode);
}
function loadTasks() {
const allTasks = JSON.parse(localStorage.getItem('tasks')) || [];
tasks = allTasks.filter(task => task.userId === currentUser.id);
checkForExpiredTasks(); // Check for expired tasks on load
filterAndRenderTasks();
}
function saveTasks() {
const allTasks = JSON.parse(localStorage.getItem('tasks')) || [];
// Remove current user's tasks
const otherUsersTasks = allTasks.filter(task => task.userId !== currentUser.id);
// Add current user's tasks
const updatedTasks = [...otherUsersTasks, ...tasks];
localStorage.setItem('tasks', JSON.stringify(updatedTasks));
updateStats();
}
function addTask() {
const text = taskInput.value.trim();
if (!text) return;
// Get category - if "other" and custom category is provided, use that
let category = categorySelect.value;
if (category === 'other' && customCategoryInput.value.trim()) {
category = customCategoryInput.value.trim();
}
const newTask = {
id: Date.now().toString(),
userId: currentUser.id,
text,
completed: false,
priority: prioritySelect.value,
category: category,
dueDate: dueDateInput.value || null,
createdAt: new Date().toISOString(),
toBeDeleted: false // Flag for auto-deletion
};
tasks.unshift(newTask);
saveTasks();
filterAndRenderTasks();
// Clear inputs
taskInput.value = '';
dueDateInput.value = '';
customCategoryInput.value = '';
customCategoryInput.style.display = 'none';
}
function checkForExpiredTasks() {
const now = new Date();
const thirtyDaysAgo = new Date(now.setDate(now.getDate() - 30)).toISOString();
tasks = tasks.filter(task => {
// If task is completed and older than 30 days, mark for deletion
if (task.completed && task.createdAt < thirtyDaysAgo) {
return false;
}
return true;
});
saveTasks();
filterAndRenderTasks();
}
function filterAndRenderTasks() {
let filteredTasks = [...tasks];
// Apply view filter
switch (currentView) {
case 'today':
const today = new Date().toISOString().split('T')[0];
filteredTasks = filteredTasks.filter(task => task.dueDate === today);
taskListTitle.textContent = 'Today\'s Tasks';
break;
case 'upcoming':
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const tomorrowStr = tomorrow.toISOString().split('T')[0];
filteredTasks = filteredTasks.filter(task =>
task.dueDate && task.dueDate >= tomorrowStr
);
taskListTitle.textContent = 'Upcoming Tasks';
break;
case 'completed':
filteredTasks = filteredTasks.filter(task => task.completed);
taskListTitle.textContent = 'Completed Tasks';
break;
case 'past':
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const yesterdayStr = yesterday.toISOString().split('T')[0];
filteredTasks = filteredTasks.filter(task =>
task.dueDate && task.dueDate < yesterdayStr
);
taskListTitle.textContent = 'Past Tasks';
break;
default:
taskListTitle.textContent = 'All Tasks';
}
// Apply category filter
if (currentCategory !== 'all') {
filteredTasks = filteredTasks.filter(task => task.category === currentCategory);
}
// Apply search filter
const searchTerm = taskSearch.value.toLowerCase();
if (searchTerm) {
filteredTasks = filteredTasks.filter(task =>
task.text.toLowerCase().includes(searchTerm)
);
}
// Apply sorting
const sortBy = sortBySelect.value;
filteredTasks.sort((a, b) => {
if (sortBy === 'priority') {
const priorityOrder = { high: 3, medium: 2, low: 1 };
return priorityOrder[b.priority] - priorityOrder[a.priority];
} else if (sortBy === 'dueDate') {
if (!a.dueDate && !b.dueDate) return 0;
if (!a.dueDate) return 1;
if (!b.dueDate) return -1;
return a.dueDate.localeCompare(b.dueDate);
} else { // creationDate
return new Date(b.createdAt) - new Date(a.createdAt);
}
});
renderTasks(filteredTasks);
}
function renderTasks(tasksToRender = tasks) {
taskList.innerHTML = '';
if (tasksToRender.length === 0) {
taskList.innerHTML = '<p class="no-tasks">No tasks found</p>';
return;
}
tasksToRender.forEach(task => {
const taskItem = document.createElement('li');
taskItem.className = `task-item ${task.completed ? 'completed' : ''}`;
taskItem.draggable = true;
taskItem.setAttribute('data-id', task.id);
// Check if task is overdue
const today = new Date().toISOString().split('T')[0];
const isOverdue = task.dueDate && task.dueDate < today && !task.completed;
const isDueToday = task.dueDate && task.dueDate === today && !task.completed;
taskItem.innerHTML = `
<input type="checkbox" class="task-checkbox" ${task.completed ? 'checked' : ''}>
<div class="task-content">
<div class="task-text">${task.text}</div>
<div class="task-meta">
<span class="task-priority">
<span class="task-priority-badge ${task.priority}"></span>
${task.priority.charAt(0).toUpperCase() + task.priority.slice(1)}
</span>
<span class="task-category">
<span class="task-category-badge ${task.category.toLowerCase()}"></span>
${task.category}
</span>
${task.dueDate ? `
<span class="task-due-date ${isOverdue ? 'overdue' : ''} ${isDueToday ? 'today' : ''}">
<i class="fas fa-calendar-alt"></i>
${formatDate(task.dueDate)} ${isOverdue ? '(Overdue)' : ''} ${isDueToday ? '(Today)' : ''}
</span>
` : ''}
</div>
</div>
<div class="task-actions">
<button class="task-btn edit-btn" title="Edit Task">
<i class="fas fa-edit"></i>
</button>
<button class="task-btn delete-btn" title="Delete Task">
<i class="fas fa-trash-alt"></i>
</button>
</div>
`;
taskList.appendChild(taskItem);
// Add event listeners to the new elements
const checkbox = taskItem.querySelector('.task-checkbox');
checkbox.addEventListener('change', () => toggleTaskComplete(task.id));
const editBtn = taskItem.querySelector('.edit-btn');
editBtn.addEventListener('click', () => openEditModal(task));
const deleteBtn = taskItem.querySelector('.delete-btn');
deleteBtn.addEventListener('click', () => deleteTask(task.id));
});
}
function toggleTaskComplete(taskId) {
const taskIndex = tasks.findIndex(task => task.id === taskId);
if (taskIndex !== -1) {
tasks[taskIndex].completed = !tasks[taskIndex].completed;
saveTasks();
filterAndRenderTasks();
// Check for due date reminders
checkForReminders();
}
}
function deleteTask(taskId) {
if (confirm('Are you sure you want to delete this task?')) {
tasks = tasks.filter(task => task.id !== taskId);
saveTasks();
filterAndRenderTasks();
}
}
function openEditModal(task) {
currentEditTaskId = task.id;
editTaskText.value = task.text;
editPriority.value = task.priority;
editCategory.value = task.category;
editDueDate.value = task.dueDate || '';
editTaskModal.style.display = 'block';
}
function saveEditedTask(e) {
e.preventDefault();
const taskIndex = tasks.findIndex(task => task.id === currentEditTaskId);
if (taskIndex !== -1) {
tasks[taskIndex].text = editTaskText.value.trim();
tasks[taskIndex].priority = editPriority.value;
tasks[taskIndex].category = editCategory.value;
tasks[taskIndex].dueDate = editDueDate.value || null;
saveTasks();
filterAndRenderTasks();
editTaskModal.style.display = 'none';
}
}
function updateStats() {
const total = tasks.length;
const completed = tasks.filter(task => task.completed).length;
const pending = total - completed;
const completionPercentage = total > 0 ? Math.round((completed / total) * 100) : 0;
totalTasksSpan.textContent = total;
completedTasksSpan.textContent = completed;
pendingTasksSpan.textContent = pending;
progressCircle.style.strokeDasharray = `${completionPercentage}, 100`;
progressPercentage.textContent = `${completionPercentage}%`;
}
function updateActiveViewButton() {
viewButtons.forEach(button => {
if (button.getAttribute('data-view') === currentView) {
button.classList.add('active');
} else {
button.classList.remove('active');
}
});
}
function updateActiveCategoryItem() {
categoryItems.forEach(item => {
if (item.getAttribute('data-category') === currentCategory) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
}
function formatDate(dateString) {
if (!dateString) return '';
const options = { year: 'numeric', month: 'short', day: 'numeric' };
return new Date(dateString).toLocaleDateString(undefined, options);
}
function checkForReminders() {
const today = new Date().toISOString().split('T')[0];
const overdueTasks = tasks.filter(task =>
task.dueDate &&
task.dueDate < today &&
!task.completed
);
const dueTodayTasks = tasks.filter(task =>
task.dueDate &&
task.dueDate === today &&
!task.completed
);
if (overdueTasks.length > 0 || dueTodayTasks.length > 0) {
let reminderMessage = '';
if (overdueTasks.length > 0) {
reminderMessage += `You have ${overdueTasks.length} overdue task(s):\n`;
overdueTasks.forEach(task => {
reminderMessage += `- ${task.text} (due ${formatDate(task.dueDate)})\n`;
});
}
if (dueTodayTasks.length > 0) {
if (reminderMessage) reminderMessage += '\n';
reminderMessage += `You have ${dueTodayTasks.length} task(s) due today:\n`;
dueTodayTasks.forEach(task => {
reminderMessage += `- ${task.text}\n`;
});
}
alert(reminderMessage);
}
}
// Drag and Drop functions
function handleDragStart(e) {
draggedItem = e.target.closest('.task-item');
e.target.style.opacity = '0.5';
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', draggedItem.innerHTML);
}
function handleDragOver(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
const taskItem = e.target.closest('.task-item');
if (taskItem && taskItem !== draggedItem) {
const rect = taskItem.getBoundingClientRect();
const midpoint = rect.top + rect.height / 2;
if (e.clientY < midpoint) {
taskItem.classList.add('over');
taskItem.style.borderTop = '2px solid var(--primary-color)';
taskItem.style.borderBottom = 'none';
} else {
taskItem.classList.add('over');
taskItem.style.borderBottom = '2px solid var(--primary-color)';
taskItem.style.borderTop = 'none';
}
}
}
function handleDragLeave(e) {
const taskItem = e.target.closest('.task-item');
if (taskItem) {
taskItem.classList.remove('over');
taskItem.style.borderTop = 'none';
taskItem.style.borderBottom = '1px solid var(--border-color)';
}
}
function handleDrop(e) {
e.preventDefault();
e.stopPropagation();
const taskItem = e.target.closest('.task-item');
if (taskItem && taskItem !== draggedItem) {
const rect = taskItem.getBoundingClientRect();
const midpoint = rect.top + rect.height / 2;
// Get the IDs of the dragged item and the target item
const draggedId = draggedItem.getAttribute('data-id');
const targetId = taskItem.getAttribute('data-id');
// Find the indices of the tasks in the array
const draggedIndex = tasks.findIndex(task => task.id === draggedId);
const targetIndex = tasks.findIndex(task => task.id === targetId);
if (draggedIndex !== -1 && targetIndex !== -1) {
// Remove the dragged task from its current position
const [movedTask] = tasks.splice(draggedIndex, 1);
// Insert it before or after the target based on drop position
if (e.clientY < midpoint) {
// Insert before the target
tasks.splice(targetIndex, 0, movedTask);
} else {
// Insert after the target
tasks.splice(targetIndex + 1, 0, movedTask);
}
saveTasks();
filterAndRenderTasks();
}
}
// Reset styles
const allItems = document.querySelectorAll('.task-item');
allItems.forEach(item => {
item.classList.remove('over');
item.style.borderTop = 'none';
item.style.borderBottom = '1px solid var(--border-color)';
});
}
function handleDragEnd() {
// Reset styles
const allItems = document.querySelectorAll('.task-item');
allItems.forEach(item => {
item.style.opacity = '1';
item.classList.remove('over');
item.style.borderTop = 'none';
item.style.borderBottom = '1px solid var(--border-color)';
});
draggedItem = null;
}
});