-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
862 lines (744 loc) · 28.7 KB
/
Copy pathscript.js
File metadata and controls
862 lines (744 loc) · 28.7 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
// Task statistics functionality with proper DOM manipulation
function createTaskStats() {
// Create container
const statsContainer = document.createElement('div');
statsContainer.id = 'task-stats';
statsContainer.className = 'stats-container';
// Create stat items using proper DOM methods
const statData = [
{ id: 'total-tasks', label: 'Total Tasks' },
{ id: 'completed-tasks', label: 'Completed' },
{ id: 'pending-tasks', label: 'Pending' }
];
statData.forEach(stat => {
const statItem = document.createElement('div');
statItem.className = 'stat-item';
const statNumber = document.createElement('span');
statNumber.className = 'stat-number';
statNumber.id = stat.id;
statNumber.textContent = '0';
const statLabel = document.createElement('span');
statLabel.className = 'stat-label';
statLabel.textContent = stat.label;
statItem.appendChild(statNumber);
statItem.appendChild(statLabel);
statsContainer.appendChild(statItem);
});
// FIXED: Insert after the VIP header, not the h1
const mainContent = document.getElementById('main-content');
const vipHeader = mainContent.querySelector('.vip-header');
vipHeader.insertAdjacentElement('afterend', statsContainer);
}
function updateTaskStats() {
const tasks = document.querySelectorAll('#tasks li');
const completedTasks = document.querySelectorAll('#tasks input[type="checkbox"]:checked');
// Safely update stats if elements exist
const totalEl = document.getElementById('total-tasks');
const completedEl = document.getElementById('completed-tasks');
const pendingEl = document.getElementById('pending-tasks');
if (totalEl && completedEl && pendingEl) {
totalEl.textContent = tasks.length;
completedEl.textContent = completedTasks.length;
pendingEl.textContent = tasks.length - completedTasks.length;
}
}
// ==================== FLOATING ACTION BUTTON ====================
function createFloatingActionButton() {
const fab = document.createElement('button');
fab.id = 'fab-add-task';
fab.className = 'fab';
fab.innerHTML = '+';
fab.setAttribute('aria-label', 'Add new task');
// Create the form container (initially hidden)
const formContainer = document.createElement('div');
formContainer.id = 'fab-form-container';
formContainer.className = 'fab-form-container hidden';
// Move the existing form into a temporary variable
const existingForm = document.getElementById('create-task-form');
if (existingForm) {
// Create form header
const formHeader = document.createElement('div');
formHeader.className = 'fab-form-header';
formHeader.innerHTML = `
<h3 class="fab-form-title">Add New Task</h3>
<p class="fab-form-subtitle">Fill in the details below</p>
`;
// Enhanced close button
const closeBtn = document.createElement('button');
closeBtn.type = 'button';
closeBtn.className = 'fab-form-close';
closeBtn.innerHTML = '×';
closeBtn.setAttribute('aria-label', 'Close form');
closeBtn.addEventListener('click', () => {
formContainer.classList.add('hidden');
fab.classList.remove('hidden');
});
// Create form body
const formBody = document.createElement('div');
formBody.className = 'fab-form-body';
// Move the existing form into the body
formBody.appendChild(existingForm);
// Add close button to header
formHeader.appendChild(closeBtn);
// Assemble the form container
formContainer.appendChild(formHeader);
formContainer.appendChild(formBody);
// Add proper labels to form inputs based on your HTML structure
addFormLabels(existingForm);
}
// FAB click handler
fab.addEventListener('click', () => {
formContainer.classList.remove('hidden');
fab.classList.add('hidden');
// Auto-focus on the input field for better UX
const input = document.getElementById('new-task-description');
if (input) input.focus();
});
// Add to main content
const mainContent = document.getElementById('main-content');
mainContent.appendChild(fab);
mainContent.appendChild(formContainer);
}
// Helper function to add labels to form inputs
function addFormLabels(form) {
// Get all form rows
const formRows = form.querySelectorAll('.form-row');
// First row: Task User and Task Description
const firstRow = formRows[0];
const userInput = firstRow.querySelector('#task-user');
const descInput = firstRow.querySelector('#new-task-description');
if (firstRow && userInput && descInput) {
// Clear the row and rebuild with labels
firstRow.innerHTML = '';
// User input group
const userGroup = document.createElement('div');
userGroup.className = 'form-input-group';
userGroup.innerHTML = `
<label for="task-user" class="form-label">Assigned To</label>
<input type="text" id="task-user" placeholder="e.g. Mohamed">
`;
// Description input group
const descGroup = document.createElement('div');
descGroup.className = 'form-input-group';
descGroup.innerHTML = `
<label for="new-task-description" class="form-label required">Task Description</label>
<input type="text" id="new-task-description" placeholder="What needs to be done?" required>
`;
firstRow.appendChild(userGroup);
firstRow.appendChild(descGroup);
}
// Second row: Priority and Due Date
const secondRow = formRows[1];
const prioritySelect = secondRow.querySelector('#priority-level');
const dateInput = secondRow.querySelector('#due-date');
if (secondRow && prioritySelect && dateInput) {
// Clear the row and rebuild with labels
secondRow.innerHTML = '';
// Priority select group
const priorityGroup = document.createElement('div');
priorityGroup.className = 'form-input-group';
priorityGroup.innerHTML = `
<label for="priority-level" class="form-label">Priority Level</label>
<select id="priority-level">
<option value="low">Low Priority</option>
<option value="medium">Medium Priority</option>
<option value="high">High Priority</option>
</select>
`;
// Date input group
const dateGroup = document.createElement('div');
dateGroup.className = 'form-input-group';
dateGroup.innerHTML = `
<label for="due-date" class="form-label required">Due Date</label>
<input type="date" id="due-date" required>
`;
secondRow.appendChild(priorityGroup);
secondRow.appendChild(dateGroup);
}
// Update submit button text
const submitBtn = form.querySelector('#add-task-btn');
if (submitBtn) {
submitBtn.textContent = 'Create Task';
}
}
// ==================== PREMIUM SIDEBAR FUNCTIONS ====================
// Create premium sidebar with features
function createPremiumSidebar() {
const sidebar = document.createElement('div');
sidebar.className = 'sidebar';
// Statistics Section - MOVED INTO SIDEBAR
const statsSection = document.createElement('div');
statsSection.id = 'task-stats'; // Keep the same ID
statsSection.className = 'stats-sidebar'; // Updated class
// Create stat items using your existing structure
const statData = [
{ id: 'total-tasks', label: 'Total Tasks' },
{ id: 'completed-tasks', label: 'Completed' },
{ id: 'pending-tasks', label: 'Pending' }
];
statData.forEach(stat => {
const statItem = document.createElement('div');
statItem.className = 'stat-item';
const statNumber = document.createElement('span');
statNumber.className = 'stat-number';
statNumber.id = stat.id;
statNumber.textContent = '0';
const statLabel = document.createElement('span');
statLabel.className = 'stat-label';
statLabel.textContent = stat.label;
statItem.appendChild(statNumber);
statItem.appendChild(statLabel);
statsSection.appendChild(statItem);
});
// Quick Actions Section
const quickActions = document.createElement('div');
quickActions.className = 'quick-actions-sidebar';
quickActions.innerHTML = `
<h3>Quick Actions</h3>
<button id="clear-completed" class="sidebar-btn">🗑️ Clear Completed</button>
<button id="mark-all-done" class="sidebar-btn">✅ Mark All Done</button>
<button id="export-tasks" class="sidebar-btn">📊 Export to Excel</button>
`;
// Due Soon Section
const dueSoon = document.createElement('div');
dueSoon.className = 'due-soon-sidebar';
dueSoon.innerHTML = `
<h3>🕒 Due Soon</h3>
<div id="due-list" class="due-list"></div>
`;
// Productivity Tip Section
const tipSection = document.createElement('div');
tipSection.className = 'tip-sidebar';
tipSection.innerHTML = `
<div class="tip-icon">💡</div>
<p id="tip-text">Break large tasks into smaller steps!</p>
`;
// Assemble sidebar - STATS NOW INSIDE SIDEBAR
sidebar.appendChild(statsSection);
sidebar.appendChild(quickActions);
sidebar.appendChild(dueSoon);
sidebar.appendChild(tipSection);
// Create main content wrapper
const mainArea = document.createElement('div');
mainArea.className = 'main-area';
// Move existing content to main area BUT EXCLUDE THE FORM
const mainContent = document.getElementById('main-content');
const elementsToMove = Array.from(mainContent.children).filter(child =>
!child.classList.contains('vip-header') &&
child.id !== 'task-stats' &&
child.id !== 'create-task-form' // EXCLUDE THE FORM
);
elementsToMove.forEach(element => {
mainArea.appendChild(element);
});
// Create layout container
const appLayout = document.createElement('div');
appLayout.className = 'app-layout';
appLayout.appendChild(sidebar);
appLayout.appendChild(mainArea);
// Insert after VIP header
const vipHeader = document.querySelector('.vip-header');
vipHeader.insertAdjacentElement('afterend', appLayout);
// Add event listeners for new buttons
addSidebarEventListeners();
}
// Add sidebar functionality
function addSidebarEventListeners() {
document.getElementById('clear-completed')?.addEventListener('click', clearCompletedTasks);
document.getElementById('mark-all-done')?.addEventListener('click', markAllDone);
document.getElementById('export-tasks')?.addEventListener('click', exportTasks);
}
// Sidebar functions
// Sidebar functions
function clearCompletedTasks() {
const completedTasks = document.querySelectorAll('#tasks input[type="checkbox"]:checked');
completedTasks.forEach(checkbox => {
const li = checkbox.closest('li');
const taskId = li && li.dataset.taskId;
if (!taskId) {
// Fallback: remove from UI if no id
li?.remove();
updateTaskStats();
updateDueSoon();
return;
}
fetch(`https://taskzilla-vz2d.onrender.com/tasks/${taskId}`, { method: 'DELETE' })
.then(res => {
if (!res.ok) throw new Error('Delete failed');
li.remove();
updateTaskStats(); // Update the stats in sidebar
updateDueSoon(); // Update due soon section
})
.catch(error => {
console.error('Error deleting task:', error);
// Fallback: remove from UI anyway
li.remove();
updateTaskStats();
updateDueSoon();
});
});
}
function markAllDone() {
const checkboxes = document.querySelectorAll('#tasks input[type="checkbox"]:not(:checked)');
const updatePromises = [];
checkboxes.forEach(checkbox => {
const li = checkbox.closest('li');
const taskId = li && li.dataset.taskId;
checkbox.checked = true;
if (!taskId) {
// update UI only if no id
const taskContent = li.querySelector('.task-content');
if (taskContent) taskContent.style.textDecoration = "line-through";
return;
}
// Update in backend
const updatePromise = fetch(`https://taskzilla-vz2d.onrender.com/tasks/${taskId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ completed: true })
})
.then(res => {
if (!res.ok) throw new Error('Patch failed');
// Update UI
const taskContent = li.querySelector('.task-content');
if (taskContent) {
taskContent.style.textDecoration = "line-through";
}
})
.catch(error => {
console.error('Error updating task:', error);
// Still update UI even if backend fails
const taskContent = li.querySelector('.task-content');
if (taskContent) {
taskContent.style.textDecoration = "line-through";
}
});
updatePromises.push(updatePromise);
});
// Wait for all updates to complete
Promise.all(updatePromises).then(() => {
updateTaskStats(); // Update the stats in sidebar
updateDueSoon(); // Update due soon section
});
}
function exportTasks() {
const tasks = Array.from(document.querySelectorAll('#tasks li')).map(li => {
const description = li.querySelector('.task-content').textContent.split(' (Due:')[0];
const completed = li.querySelector('input[type="checkbox"]').checked ? 'Yes' : 'No';
const dueDate = li.dataset.dueDate || 'No date';
const priority = li.style.color === 'red' ? 'High' :
li.style.color === 'orange' ? 'Medium' :
li.style.color === 'green' ? 'Low' : 'Unknown';
return {
Description: description,
Completed: completed,
'Due Date': dueDate,
Priority: priority
};
});
// Create CSV content (Excel can open CSV files)
const headers = ['Description', 'Completed', 'Due Date', 'Priority'];
const csvContent = [
headers.join(','), // Header row
...tasks.map(task => [
`"${task.Description.replace(/"/g, '""')}"`, // Escape quotes in description
task.Completed,
`"${task['Due Date']}"`,
task.Priority
].join(','))
].join('\n');
// Create and download the file
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `taskzilla-export-${new Date().toISOString().split('T')[0]}.csv`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Update due soon list
function updateDueSoon() {
const dueList = document.getElementById('due-list');
if (!dueList) return;
const tasks = Array.from(document.querySelectorAll('#tasks li'));
const today = new Date();
const dueSoon = tasks.filter(li => {
const dueDate = new Date(li.dataset.dueDate);
const diffTime = dueDate - today;
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
return diffDays <= 3 && diffDays >= 0;
}).slice(0, 3); // Show only 3 most urgent
dueList.innerHTML = dueSoon.map(li => {
const text = li.querySelector('.task-content').textContent;
const dueDate = li.dataset.dueDate;
return `<div class="due-item">${text.split(' (Due:')[0]}<br><small>Due: ${dueDate}</small></div>`;
}).join('') || '<div class="due-item">No urgent tasks! 🎉</div>';
}
// Update productivity tip
function updateProductivityTip() {
const tips = [
"Eat the frog! Do your most important task first.",
"Break large tasks into smaller, manageable steps.",
"Use the Pomodoro technique: 25min work, 5min break.",
"Review your tasks at the end of each day.",
"Focus on one task at a time for better productivity.",
"Delegate tasks when possible to free up your time.",
"Set clear deadlines to stay motivated and focused."
];
const tipText = document.getElementById('tip-text');
if (tipText) {
const randomTip = tips[Math.floor(Math.random() * tips.length)];
tipText.textContent = randomTip;
}
}
// ==================== COLORFUL CLOCK FUNCTIONALITY ====================
function createClock() {
const clockContainer = document.createElement('div');
clockContainer.id = 'task-clock';
clockContainer.className = 'task-clock';
const timeDisplay = document.createElement('div');
timeDisplay.className = 'clock-time';
const dateDisplay = document.createElement('div');
dateDisplay.className = 'clock-date';
const greetingDisplay = document.createElement('div');
greetingDisplay.className = 'clock-greeting';
clockContainer.appendChild(timeDisplay);
clockContainer.appendChild(dateDisplay);
clockContainer.appendChild(greetingDisplay);
// Insert above the task list
const taskList = document.getElementById('list');
taskList.parentNode.insertBefore(clockContainer, taskList);
// Update clock every second
function updateClock() {
const now = new Date();
const hour = now.getHours();
// Time formatting
const timeOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit' };
const timeString = now.toLocaleTimeString([], timeOptions);
// Date formatting
const dateOptions = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const dateString = now.toLocaleDateString([], dateOptions);
// Dynamic greeting based on time
let greeting = '';
if (hour < 12) greeting = '🌅 Good Morning!';
else if (hour < 18) greeting = '☀️ Good Afternoon!';
else greeting = '🌙 Good Evening!';
timeDisplay.textContent = timeString;
dateDisplay.textContent = dateString;
greetingDisplay.textContent = greeting;
// Dynamic color change based on time
updateClockColors(hour);
}
function updateClockColors(hour) {
const clock = document.getElementById('task-clock');
const colors = getTimeBasedColors(hour);
clock.style.background = colors.background;
clock.style.borderColor = colors.border;
}
function getTimeBasedColors(hour) {
if (hour < 6) return { // Night
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
border: '#5a6fd8'
};
if (hour < 12) return { // Morning
background: 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
border: '#ff7b7f'
};
if (hour < 18) return { // Afternoon
background: 'linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%)',
border: '#8bb3fc'
};
return { // Evening
background: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
border: '#f95c8b'
};
}
updateClock();
setInterval(updateClock, 1000);
}
// ==================== UPDATED DOMCONTENTLOADED ====================
document.addEventListener("DOMContentLoaded", () => {
// Create premium sidebar with integrated statistics
createPremiumSidebar();
// Create floating action button
createFloatingActionButton();
const taskList = document.getElementById("tasks");
const form = document.getElementById("create-task-form");
const input = document.getElementById("new-task-description");
const prioritySelect = document.getElementById("priority-level");
const dateInput = document.getElementById("due-date");
const userInput = document.getElementById("task-user");
const sortDateBtn = document.getElementById("sort-date-btn");
const sortBtn = document.getElementById("sort-btn");
const BASE_URL = "https://taskzilla-vz2d.onrender.com/tasks";
//clock
createClock();
// Load tasks from backend
fetch(BASE_URL)
.then(res => {
if (!res.ok) throw new Error(`Failed to fetch tasks: ${res.status}`);
return res.json();
})
.then(tasks => {
// Clear any existing list before rendering
taskList.innerHTML = '';
tasks.forEach(task => renderTask(task));
updateTaskStats();
updateDueSoon(); // Initialize due soon section
updateProductivityTip(); // Initialize tips
})
.catch(err => {
console.error('Error loading tasks:', err);
// keep the UI usable even if backend fails
});
// Render a task
function renderTask(task) {
const li = document.createElement("li");
li.className = "task-item";
li.setAttribute("data-due-date", task.dueDate);
// <-- IMPORTANT: store the id so other actions can reference it
if (task.id !== undefined) li.dataset.taskId = task.id;
li.style.position = "relative";
// Apply priority color
if (task.priority === "high") li.style.color = "red";
else if (task.priority === "medium") li.style.color = "orange";
else if (task.priority === "low") li.style.color = "green";
// Task content container
const taskContent = document.createElement("div");
taskContent.className = "task-content";
taskContent.textContent = `${task.description} (Due: ${task.dueDate}) - Assigned to: ${task.assignedUser}`;
const badge = document.createElement("span");
badge.classList.add("priority-badge", `priority-${task.priority}`);
badge.textContent = task.priority.charAt(0).toUpperCase() + task.priority.slice(1);
taskContent.appendChild(badge);
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = task.completed;
checkbox.style.marginRight = "10px";
checkbox.addEventListener("change", () => {
taskContent.style.textDecoration = checkbox.checked ? "line-through" : "none";
const id = li.dataset.taskId;
if (!id) {
updateTaskStats();
updateDueSoon();
return;
}
fetch(`https://taskzilla-vz2d.onrender.com/tasks/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ completed: checkbox.checked })
}).then(res => {
if (!res.ok) throw new Error('Failed to update completed status');
updateTaskStats();
updateDueSoon(); // Update due soon when tasks change
}).catch(err => {
console.error('Error patching completion:', err);
updateTaskStats();
updateDueSoon();
});
});
// Action menu button
const actionMenuBtn = document.createElement("button");
actionMenuBtn.textContent = "⋮";
actionMenuBtn.className = "action-menu";
// Dropdown menu
const menu = document.createElement("div");
menu.className = "action-dropdown";
menu.style.display = "none";
const editOption = document.createElement("button");
editOption.textContent = "✏️ Edit Task";
editOption.addEventListener("click", () => {
const newTask = prompt("Edit task:", task.description);
const newDate = prompt("Edit due date:", task.dueDate);
const newUser = prompt("Edit assigned user:", task.assignedUser);
if (newTask && newDate && newUser) {
const id = li.dataset.taskId;
if (!id) {
// UI-only fallback
taskContent.textContent = `${newTask} (Due: ${newDate}) - Assigned to: ${newUser}`;
taskContent.appendChild(badge);
li.setAttribute("data-due-date", newDate);
updateDueSoon();
menu.style.display = "none";
return;
}
fetch(`https://taskzilla-vz2d.onrender.com/tasks/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
description: newTask,
dueDate: newDate,
assignedUser: newUser
})
}).then(res => {
if (!res.ok) throw new Error('Failed to patch task');
taskContent.textContent = `${newTask} (Due: ${newDate}) - Assigned to: ${newUser}`;
taskContent.appendChild(badge);
li.setAttribute("data-due-date", newDate);
updateDueSoon(); // Update due soon when tasks change
}).catch(err => {
console.error('Error editing task:', err);
});
}
menu.style.display = "none";
});
const deleteOption = document.createElement("button");
deleteOption.textContent = "❌ Delete Task";
deleteOption.addEventListener("click", () => {
const id = li.dataset.taskId;
if (!id) {
li.remove();
updateTaskStats();
updateDueSoon();
menu.style.display = "none";
return;
}
fetch(`https://taskzilla-vz2d.onrender.com/tasks/${id}`, {
method: "DELETE"
}).then(res => {
if (!res.ok) throw new Error('Failed to delete task');
li.remove();
updateTaskStats();
updateDueSoon(); // Update due soon when tasks change
}).catch(err => {
console.error('Error deleting task:', err);
// fallback: remove UI
li.remove();
updateTaskStats();
updateDueSoon();
});
menu.style.display = "none";
});
menu.appendChild(editOption);
menu.appendChild(deleteOption);
actionMenuBtn.addEventListener("click", () => {
menu.style.display = menu.style.display === "none" ? "block" : "none";
});
const rightSide = document.createElement("div");
rightSide.className = "task-controls";
rightSide.appendChild(actionMenuBtn);
rightSide.appendChild(menu);
li.appendChild(checkbox);
li.appendChild(taskContent);
li.appendChild(rightSide);
taskList.appendChild(li);
// Apply strikethrough if task is completed
if (task.completed) {
taskContent.style.textDecoration = "line-through";
}
updateTaskStats();
}
// Submit new task
form.addEventListener("submit", function (event) {
event.preventDefault();
const newTask = {
description: input.value,
dueDate: dateInput.value,
priority: prioritySelect.value,
assignedUser: userInput.value,
completed: false
};
fetch(BASE_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newTask)
})
.then(res => {
if (!res.ok) throw new Error(`Failed to create task: ${res.status}`);
return res.json();
})
.then(task => {
// render returned task (with id)
renderTask(task);
updateTaskStats();
updateDueSoon(); // Update due soon when tasks change
// Close the form after successful submission
const formContainer = document.getElementById('fab-form-container');
const fab = document.getElementById('fab-add-task');
if (formContainer && fab) {
formContainer.classList.add('hidden');
fab.classList.remove('hidden');
}
})
.catch(err => {
console.error('Error creating task:', err);
// Optionally, show a user-facing error
});
input.value = "";
userInput.value = "";
prioritySelect.value = "low";
dateInput.value = "";
});
// Sort by due date
sortDateBtn.addEventListener("click", () => {
const tasks = Array.from(document.querySelectorAll("#tasks li"));
tasks.sort((a, b) => {
const dateA = new Date(a.dataset.dueDate);
const dateB = new Date(b.dataset.dueDate);
return dateA - dateB;
});
taskList.innerHTML = "";
tasks.forEach(task => taskList.appendChild(task));
});
// Sort by priority
sortBtn.addEventListener("click", () => {
const tasks = Array.from(document.querySelectorAll("#tasks li"));
const priorityOrder = { high: 1, medium: 2, low: 3 };
const getPriorityValue = (li) => {
const color = li.style.color;
if (color === "red") return priorityOrder.high;
if (color === "orange") return priorityOrder.medium;
if (color === "green") return priorityOrder.low;
return 4;
};
tasks.sort((a, b) => getPriorityValue(a) - getPriorityValue(b));
taskList.innerHTML = "";
tasks.forEach(task => taskList.appendChild(task));
});
// Update sidebar features periodically
setInterval(() => {
updateDueSoon();
updateProductivityTip();
}, 30000);
});
// Auto-close dropdown when clicking outside
document.addEventListener("click", (event) => {
const allMenus = document.querySelectorAll(".action-dropdown");
allMenus.forEach(menu => {
const toggleButton = menu.previousElementSibling;
if (!menu.contains(event.target) && !toggleButton.contains(event.target)) {
menu.style.display = "none";
}
});
});
// ---- Dynamic Quote Section ----
window.addEventListener('load', function() {
console.log('Window fully loaded, initializing quotes...');
const quoteText = document.getElementById("quote-text");
const quoteAuthor = document.getElementById("quote-author");
if (!quoteText || !quoteAuthor) {
console.error('Critical: Quote elements not found even after window.load');
return;
}
const RENDER_BACKEND_URL = "https://taskzilla-vz2d.onrender.com";
async function fetchQuote() {
try {
console.log('Fetching quote from backend...');
const response = await fetch(`${RENDER_BACKEND_URL}/api/quote`);
if (!response.ok) throw new Error(`Status: ${response.status}`);
const data = await response.json();
displayQuote(data.content, data.author);
} catch (error) {
console.error('Failed to fetch quote:', error);
displayQuote("Persistence conquers all challenges", "TaskZilla Wisdom");
}
}
function displayQuote(text, author) {
quoteText.textContent = `"${text}"`;
quoteAuthor.textContent = `— ${author}`;
}
fetchQuote();
setInterval(fetchQuote, 60000);
});