-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1399 lines (1251 loc) · 56.6 KB
/
Copy pathapp.js
File metadata and controls
1399 lines (1251 loc) · 56.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
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
1000
/* ==========================================================================
AuraStudy Core Application Script
========================================================================== */
// --- Global State Store ---
let state = {
settings: {
userName: "Sanidhya",
userGrade: "B.Tech Computer Science",
attendanceTarget: 75
},
subjects: [],
assignments: [],
planner: [],
notes: []
};
// --- Mock / Demo Data (Loaded on First Run) ---
const demoSubjects = [
{ id: "sub-1", name: "Computer Networks", attended: 11, total: 16 },
{ id: "sub-2", name: "Mathematics IV", attended: 14, total: 18 },
{ id: "sub-3", name: "Database Systems", attended: 15, total: 16 },
{ id: "sub-4", name: "Software Engineering", attended: 12, total: 15 }
];
const demoAssignments = [
{
id: "asn-1",
title: "Networks Lab 3 - Socket Programming",
subjectId: "sub-1",
deadline: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().slice(0, 16), // Tomorrow
priority: "high",
notes: "Implement basic TCP multi-client chat application in Python.",
isCompleted: false,
isExam: false
},
{
id: "asn-2",
title: "Maths Problem Set 4 - Fourier Transforms",
subjectId: "sub-2",
deadline: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString().slice(0, 16), // In 2 days
priority: "medium",
notes: "Solve Questions 1 to 10 on page 245.",
isCompleted: false,
isExam: false
},
{
id: "asn-3",
title: "Database SQL Queries Assignment",
subjectId: "sub-3",
deadline: new Date(Date.now() + 5 * 24 * 60 * 60 * 1000).toISOString().slice(0, 16), // In 5 days
priority: "low",
notes: "Complete schema creation and join statements sheet.",
isCompleted: false,
isExam: false
},
{
id: "asn-4",
title: "Networks Mid-Term Theory Exam",
subjectId: "sub-1",
deadline: new Date(Date.now() + 4 * 24 * 60 * 60 * 1000).toISOString().slice(0, 16), // In 4 days
priority: "high",
notes: "Chapters 1 to 4 coverage. Focus on OSI model layers.",
isCompleted: false,
isExam: true
},
{
id: "asn-5",
title: "Software Engineering Project proposal",
subjectId: "sub-4",
deadline: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString().slice(0, 16), // 2 days ago
priority: "medium",
notes: "Submit team member details and wireframes draft.",
isCompleted: true,
isExam: false
}
];
const demoPlanner = [
{ id: "tsk-1", title: "Revise routing algorithms", priority: "high", isCompleted: false, dateCreated: new Date().toDateString() },
{ id: "tsk-2", title: "Solve calculus practice sheet", priority: "medium", isCompleted: true, dateCreated: new Date().toDateString() },
{ id: "tsk-3", title: "Watch SQL indexes video lecture", priority: "medium", isCompleted: false, dateCreated: new Date().toDateString() },
{ id: "tsk-4", title: "Read Chapter 4 of Software Engineering book", priority: "low", isCompleted: false, dateCreated: new Date().toDateString() }
];
const demoNotes = [
{
id: "nte-1",
title: "Subnet Masking Tricks",
subject: "Networks",
content: "A subnet mask splits the IP address into network and host addresses.\n\nKey rules:\n- Class A: 255.0.0.0 (/8)\n- Class B: 255.255.0.0 (/16)\n- Class C: 255.255.255.0 (/24)\n\nQuick formula for hosts: 2^(32 - CIDR) - 2. Always subtract 2 for network & broadcast addresses.",
dateCreated: new Date().toLocaleDateString()
},
{
id: "nte-2",
title: "SQL Joins Cheatsheet",
subject: "Database Systems",
content: "- INNER JOIN: returns matching records in both tables.\n- LEFT JOIN: returns all records from left table + matched right.\n- RIGHT JOIN: returns all records from right table + matched left.\n- FULL OUTER JOIN: returns all records when there is a match in either table.",
dateCreated: new Date().toLocaleDateString()
},
{
id: "nte-3",
title: "SOLID Principles Notes",
subject: "Software Engineering",
content: "S - Single Responsibility: A class should have only one reason to change.\nO - Open/Closed: Open for extension, closed for modification.\nL - Liskov Substitution: Derived classes must be substitutable for base classes.\nI - Interface Segregation: Keep interfaces small and specific.\nD - Dependency Inversion: Depend on abstractions, not concretions.",
dateCreated: new Date().toLocaleDateString()
}
];
// --- Initialize State & LocalStorage ---
function loadState() {
const localData = localStorage.getItem("aurastudy_state");
if (localData) {
try {
state = JSON.parse(localData);
} catch (e) {
console.error("Error parsing local state data. Initializing demo.", e);
initDemoData();
}
} else {
initDemoData();
}
}
function initDemoData() {
state.subjects = [...demoSubjects];
state.assignments = [...demoAssignments];
state.planner = [...demoPlanner];
state.notes = [...demoNotes];
saveState();
}
function saveState() {
localStorage.setItem("aurastudy_state", JSON.stringify(state));
}
// --- Navigation View Router ---
let currentView = "dashboard";
function initRouter() {
const navLinks = document.querySelectorAll(".nav-link, .mobile-nav-link, .clickable[data-target-view]");
function changeView(viewId) {
if (!viewId) return;
currentView = viewId;
// Update URL Hash
window.location.hash = viewId;
// Toggle active views styling in side/mobile nav
document.querySelectorAll(".nav-link, .mobile-nav-link").forEach(link => {
if (link.getAttribute("data-view") === viewId) {
link.classList.add("active");
} else {
link.classList.remove("active");
}
});
// Hide all views & show target view
document.querySelectorAll(".view-section").forEach(section => {
section.classList.remove("active");
});
const activeSection = document.getElementById(`view-${viewId}`);
if (activeSection) {
activeSection.classList.add("active");
}
// Update main header title
const headerTitle = document.getElementById("view-title");
const headerActionBtn = document.getElementById("btn-header-action");
const actionText = document.getElementById("header-action-text");
// Capitalize title
headerTitle.textContent = viewId.charAt(0).toUpperCase() + viewId.slice(1);
// Adjust Header Quick Action Button depending on view
headerActionBtn.style.display = "inline-flex";
if (viewId === "dashboard") {
actionText.textContent = "New Assignment";
headerActionBtn.onclick = () => openModal("assignment");
} else if (viewId === "assignments") {
actionText.textContent = "Add Assignment";
headerActionBtn.onclick = () => openModal("assignment");
} else if (viewId === "attendance") {
actionText.textContent = "Add Subject";
headerActionBtn.onclick = () => openModal("subject");
} else if (viewId === "planner") {
actionText.textContent = "Clear Checked";
headerActionBtn.onclick = () => clearCompletedTasks();
} else if (viewId === "notes") {
actionText.textContent = "Create Note";
headerActionBtn.onclick = () => openModal("note");
} else {
headerActionBtn.style.display = "none";
}
// Render target view data
renderViewData(viewId);
}
// Bind link click triggers
navLinks.forEach(link => {
link.addEventListener("click", (e) => {
const viewTarget = link.getAttribute("data-view") || link.getAttribute("data-target-view");
changeView(viewTarget);
});
});
// Check location hash on load
const hash = window.location.hash.replace("#", "");
if (hash && ["dashboard", "assignments", "attendance", "planner", "notes"].includes(hash)) {
changeView(hash);
} else {
changeView("dashboard");
}
// Listen for hash changes
window.addEventListener("hashchange", () => {
const h = window.location.hash.replace("#", "");
if (h && h !== currentView && ["dashboard", "assignments", "attendance", "planner", "notes"].includes(h)) {
changeView(h);
}
});
}
function renderViewData(viewId) {
// Render specific view UI blocks
if (viewId === "dashboard") {
renderDashboardView();
} else if (viewId === "assignments") {
renderAssignmentsView();
} else if (viewId === "attendance") {
renderAttendanceView();
} else if (viewId === "planner") {
renderPlannerView();
} else if (viewId === "notes") {
renderNotesView();
}
// Sync active badges (e.g. pending assignment counts)
updateGlobalBadges();
}
// --- Global Badges updates ---
function updateGlobalBadges() {
const pendingAsn = state.assignments.filter(a => !a.isCompleted).length;
const badge = document.getElementById("badge-assignments-count");
if (badge) {
badge.textContent = pendingAsn;
badge.style.display = pendingAsn > 0 ? "block" : "none";
}
}
// --- 1. DASHBOARD VIEW RENDER ---
function renderDashboardView() {
// Student info details
document.querySelectorAll(".student-name-fill").forEach(el => {
el.textContent = state.settings.userName;
});
// Counts
const totalSubjects = state.subjects.length;
const pendingAssignments = state.assignments.filter(a => !a.isCompleted && !a.isExam).length;
const upcomingExams = state.assignments.filter(a => !a.isCompleted && a.isExam && new Date(a.deadline) >= new Date()).length;
// Avg attendance calculation
let avgAttendance = 0;
let totalAttended = 0;
let totalClasses = 0;
state.subjects.forEach(sub => {
totalAttended += sub.attended;
totalClasses += sub.total;
});
if (totalClasses > 0) {
avgAttendance = Math.round((totalAttended / totalClasses) * 100);
}
document.getElementById("dashboard-total-subjects").textContent = totalSubjects;
document.getElementById("dashboard-pending-assignments").textContent = pendingAssignments;
document.getElementById("dashboard-avg-attendance").textContent = avgAttendance + "%";
document.getElementById("dashboard-upcoming-exams").textContent = upcomingExams;
// Circular attendance ring in dashboard panel
const ring = document.getElementById("dashboard-attendance-ring");
const ringText = document.getElementById("dashboard-attendance-percent");
if (ring && ringText) {
ringText.textContent = avgAttendance + "%";
// stroke-dasharray is 314.16. Calculate offset.
const offset = 314.16 - (314.16 * avgAttendance) / 100;
ring.style.strokeDashoffset = offset;
// Colors warning levels
if (avgAttendance < state.settings.attendanceTarget) {
ring.style.stroke = "var(--color-danger)";
} else {
ring.style.stroke = "var(--color-success)";
}
}
// Dashboard Attendance Verdict
const verdict = document.getElementById("dashboard-attendance-verdict");
if (verdict) {
if (totalSubjects === 0) {
verdict.innerHTML = "No subjects logged yet. Go to <a href='#attendance'>Attendance</a> to get started.";
} else {
const target = state.settings.attendanceTarget;
if (avgAttendance >= target) {
// Calculate how many overall classes can be missed
let missCount = 0;
while (true) {
let nextTotal = totalClasses + (missCount + 1);
let rate = (totalAttended / nextTotal) * 100;
if (rate >= target) {
missCount++;
} else {
break;
}
}
if (missCount > 0) {
verdict.innerHTML = `Your average attendance is <strong>${avgAttendance}%</strong>. You can safely miss up to <strong>${missCount}</strong> classes across your subjects without dipping below the ${target}% target.`;
} else {
verdict.innerHTML = `Your attendance is exactly on target (<strong>${avgAttendance}%</strong>). Do not miss the next class!`;
}
} else {
// Calculate consecutive classes needed to cross target
let attendCount = 0;
while (true) {
let nextAttended = totalAttended + attendCount;
let nextTotal = totalClasses + attendCount;
let rate = (nextAttended / nextTotal) * 100;
if (rate >= target) {
break;
}
attendCount++;
}
verdict.innerHTML = `⚠️ Average attendance (<strong>${avgAttendance}%</strong>) is below your ${target}% target. You must attend the next <strong>${attendCount}</strong> consecutive classes to recover.`;
}
}
}
// Study planner progress bar
const plannerProgressText = document.getElementById("dashboard-planner-progress-text");
const plannerProgressBar = document.getElementById("dashboard-planner-progress-bar");
const todayStr = new Date().toDateString();
const todaysTasks = state.planner.filter(t => t.dateCreated === todayStr || !t.isCompleted);
const completedTasksCount = todaysTasks.filter(t => t.isCompleted).length;
const totalTasksCount = todaysTasks.length;
if (plannerProgressText && plannerProgressBar) {
plannerProgressText.textContent = `${completedTasksCount}/${totalTasksCount} Tasks`;
const percentage = totalTasksCount > 0 ? Math.round((completedTasksCount / totalTasksCount) * 100) : 0;
plannerProgressBar.style.width = percentage + "%";
}
// Render top 4 today's planner tasks in Dashboard
const dashTaskList = document.getElementById("dashboard-task-list");
if (dashTaskList) {
if (todaysTasks.length === 0) {
dashTaskList.innerHTML = `
<div class="empty-state">
<p>No study tasks created for today.</p>
<a href="#planner" class="btn btn-secondary btn-sm mt-2">Go to Planner</a>
</div>
`;
} else {
// Sort by priority (High, Medium, Low)
const sortedTasks = [...todaysTasks].sort((a, b) => {
const priorityWeight = { high: 3, medium: 2, low: 1 };
return (priorityWeight[b.priority] || 0) - (priorityWeight[a.priority] || 0);
}).slice(0, 4);
dashTaskList.innerHTML = sortedTasks.map(task => `
<div class="dashboard-task-item ${task.isCompleted ? 'completed' : ''}">
<span class="task-dot ${task.priority}"></span>
<span class="task-item-text">${task.title}</span>
</div>
`).join("");
}
}
// Urgent Assignments (due within 3 days)
const assignmentList = document.getElementById("dashboard-assignment-list");
if (assignmentList) {
const urgent = state.assignments.filter(a => {
if (a.isCompleted) return false;
const diffDays = getDiffDays(a.deadline);
return diffDays >= 0 && diffDays <= 3;
}).sort((a, b) => new Date(a.deadline) - new Date(b.deadline));
if (urgent.length === 0) {
assignmentList.innerHTML = `
<div class="empty-state">
<p>No urgent assignments due in next 3 days.</p>
</div>
`;
} else {
assignmentList.innerHTML = urgent.map(a => {
const diff = getDiffDays(a.deadline);
const countBadgeClass = diff <= 1 ? "countdown-danger" : "countdown-warning";
const countText = diff === 0 ? "Due Today" : diff === 1 ? "Due Tomorrow" : `Due in ${diff} days`;
const subName = getSubjectName(a.subjectId);
return `
<div class="dash-list-item">
<div class="dash-item-info">
<h5>${a.title}</h5>
<p>${subName} • Priority: ${a.priority.toUpperCase()}</p>
</div>
<div class="dash-item-meta">
<span class="countdown-badge ${countBadgeClass}">${countText}</span>
</div>
</div>
`;
}).join("");
}
}
// Recent Notes (Top 3)
const notesList = document.getElementById("dashboard-notes-list");
if (notesList) {
const recentNotes = [...state.notes].slice(-3).reverse();
if (recentNotes.length === 0) {
notesList.innerHTML = `
<div class="empty-state">
<p>No study notes created yet.</p>
</div>
`;
} else {
notesList.innerHTML = recentNotes.map(note => `
<div class="dash-list-item">
<div class="dash-item-info">
<h5>${note.title}</h5>
<p>Subject Tag: ${note.subject} • Created ${note.dateCreated}</p>
</div>
</div>
`).join("");
}
}
}
// --- 2. ASSIGNMENTS TRACKER VIEW RENDER ---
let activeAssignmentFilter = "all";
let assignmentSearchQuery = "";
function initAssignmentsFilter() {
const filterContainer = document.getElementById("assignment-filters");
if (filterContainer) {
filterContainer.querySelectorAll(".filter-btn").forEach(btn => {
btn.addEventListener("click", () => {
filterContainer.querySelectorAll(".filter-btn").forEach(b => b.classList.remove("active"));
btn.classList.add("active");
activeAssignmentFilter = btn.getAttribute("data-filter");
renderAssignmentsView();
});
});
}
const searchInput = document.getElementById("search-assignments");
if (searchInput) {
searchInput.addEventListener("input", (e) => {
assignmentSearchQuery = e.target.value.toLowerCase().trim();
renderAssignmentsView();
});
}
}
function renderAssignmentsView() {
const grid = document.getElementById("assignments-grid");
if (!grid) return;
let list = [...state.assignments];
const now = new Date();
// Apply search filter
if (assignmentSearchQuery) {
list = list.filter(a => {
const subName = getSubjectName(a.subjectId).toLowerCase();
return a.title.toLowerCase().includes(assignmentSearchQuery) ||
subName.includes(assignmentSearchQuery) ||
(a.notes && a.notes.toLowerCase().includes(assignmentSearchQuery));
});
}
// Apply tab filter
if (activeAssignmentFilter === "pending") {
list = list.filter(a => !a.isCompleted);
} else if (activeAssignmentFilter === "completed") {
list = list.filter(a => a.isCompleted);
} else if (activeAssignmentFilter === "overdue") {
list = list.filter(a => !a.isCompleted && new Date(a.deadline) < now);
}
// Sort by: Pending first, then deadline ascending
list.sort((a, b) => {
if (a.isCompleted !== b.isCompleted) {
return a.isCompleted ? 1 : -1;
}
return new Date(a.deadline) - new Date(b.deadline);
});
if (list.length === 0) {
grid.innerHTML = `
<div class="empty-state card" style="grid-column: 1 / -1;">
<h3>No assignments found</h3>
<p>Try modifying your search filter or add a new assignment.</p>
</div>
`;
return;
}
grid.innerHTML = list.map(a => {
const subName = getSubjectName(a.subjectId);
const deadlineDate = new Date(a.deadline);
const diffDays = getDiffDays(a.deadline);
let deadlineLabel = "";
let deadlineClass = "";
if (a.isCompleted) {
deadlineLabel = "Completed";
deadlineClass = "status-good";
} else if (diffDays < 0) {
deadlineLabel = "Overdue";
deadlineClass = "status-danger";
} else if (diffDays === 0) {
deadlineLabel = "Today";
deadlineClass = "status-danger";
} else if (diffDays === 1) {
deadlineLabel = "Tomorrow";
deadlineClass = "status-warning";
} else {
deadlineLabel = `In ${diffDays} days`;
deadlineClass = "status-good";
}
const dateOptions = { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' };
const formattedDeadline = deadlineDate.toLocaleDateString(undefined, dateOptions);
return `
<div class="card assignment-card priority-${a.priority} ${a.isCompleted ? 'completed-status' : ''}" id="card-asn-${a.id}">
<div class="card-header-row">
<span class="subject-tag">${subName}</span>
<span class="priority-badge ${a.priority}">${a.priority} Priority</span>
</div>
<div class="card-body-section">
<h4>${a.title}</h4>
<p style="font-size: 0.85rem; color: var(--text-secondary); margin-bottom: 0.75rem;">
${a.notes ? a.notes : 'No extra notes.'}
</p>
</div>
<div class="card-meta-row">
<div class="deadline-text">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
<span>Deadline: ${formattedDeadline}</span>
</div>
<div class="deadline-text">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 16.5c-1.5 1.25-2.5 3-2.5 5h20c0-2-1-3.75-2.5-5"/><circle cx="12" cy="10" r="6"/></svg>
<span>Type: ${a.isExam ? 'Exam Review' : 'Homework / Lab'}</span>
</div>
</div>
<div class="card-actions-row">
<label class="switch-label">
<input type="checkbox" class="switch-checkbox" ${a.isCompleted ? 'checked' : ''} onchange="toggleAssignmentStatus('${a.id}')">
<span class="switch-slider"></span>
<span>Completed</span>
</label>
<div style="display: flex; gap: 4px;">
<button class="btn-card-action btn-edit-action" onclick="editAssignment('${a.id}')" title="Edit">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>
</button>
<button class="btn-card-action" onclick="deleteAssignment('${a.id}')" title="Delete">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
</button>
</div>
</div>
</div>
`;
}).join("");
}
window.toggleAssignmentStatus = function(id) {
const index = state.assignments.findIndex(a => a.id === id);
if (index !== -1) {
state.assignments[index].isCompleted = !state.assignments[index].isCompleted;
saveState();
updateGlobalBadges();
// Visual feedback toast
const statusStr = state.assignments[index].isCompleted ? "completed" : "pending";
showToast(`Assignment marked as ${statusStr}!`, "success");
// Re-render
renderAssignmentsView();
}
};
window.deleteAssignment = function(id) {
if (confirm("Are you sure you want to delete this assignment?")) {
state.assignments = state.assignments.filter(a => a.id !== id);
saveState();
showToast("Assignment deleted.", "warning");
renderAssignmentsView();
}
};
window.editAssignment = function(id) {
const asn = state.assignments.find(a => a.id === id);
if (asn) {
openModal("assignment", asn);
}
};
// --- 3. ATTENDANCE VIEW RENDER ---
function renderAttendanceView() {
// Target threshold setup
const targetInput = document.getElementById("input-attendance-target");
const targetText = document.getElementById("global-target-value");
if (targetInput && targetText) {
targetInput.value = state.settings.attendanceTarget;
targetText.textContent = state.settings.attendanceTarget + "%";
}
// Overall stats display
let avgAttendance = 0;
let totalAttended = 0;
let totalClasses = 0;
state.subjects.forEach(sub => {
totalAttended += sub.attended;
totalClasses += sub.total;
});
if (totalClasses > 0) {
avgAttendance = Math.round((totalAttended / totalClasses) * 100);
}
const bannerPercent = document.getElementById("attendance-total-percentage");
const bannerBadge = document.getElementById("attendance-total-badge");
const target = state.settings.attendanceTarget;
if (bannerPercent && bannerBadge) {
bannerPercent.textContent = avgAttendance + "%";
if (state.subjects.length === 0) {
bannerBadge.textContent = "No Data";
bannerBadge.className = "status-badge status-warning";
} else if (avgAttendance >= target) {
bannerBadge.textContent = "On Track";
bannerBadge.className = "status-badge status-good";
} else {
bannerBadge.textContent = "Critical";
bannerBadge.className = "status-badge status-danger";
}
}
const grid = document.getElementById("subjects-grid");
if (!grid) return;
if (state.subjects.length === 0) {
grid.innerHTML = `
<div class="empty-state card" style="grid-column: 1 / -1;">
<h3>No subjects added yet</h3>
<p>Add subjects you are currently studying to log and simulate attendance requirements.</p>
<button class="btn btn-primary btn-sm mt-3" onclick="openModal('subject')">Add First Subject</button>
</div>
`;
return;
}
grid.innerHTML = state.subjects.map(sub => {
const percent = sub.total > 0 ? Math.round((sub.attended / sub.total) * 100) : 0;
let ringClass = "good";
if (percent < target) {
ringClass = "danger";
} else if (percent - target < 5) {
ringClass = "warning";
}
// Simulator helper calculations
let simulatorText = "";
if (sub.total === 0) {
simulatorText = "No classes recorded. Log first attendance.";
} else if (percent >= target) {
// Find max classes they can miss consecutively
let missCount = 0;
while (true) {
let nextTotal = sub.total + (missCount + 1);
let rate = (sub.attended / nextTotal) * 100;
if (rate >= target) {
missCount++;
} else {
break;
}
}
if (missCount > 0) {
simulatorText = `Safe: You can miss up to <strong>${missCount}</strong> class(es) consecutively.`;
} else {
simulatorText = "Safe: On target limit! Do not miss the next class.";
}
} else {
// Find min classes they must attend consecutively
let attendCount = 0;
while (true) {
let nextAttended = sub.attended + attendCount;
let nextTotal = sub.total + attendCount;
let rate = (nextAttended / nextTotal) * 100;
if (rate >= target) {
break;
}
attendCount++;
}
simulatorText = `Warning: Attend the next <strong>${attendCount}</strong> class(es) consecutively to cross ${target}%.`;
}
return `
<div class="card attendance-card" id="card-sub-${sub.id}">
<div class="attendance-card-header">
<h4>${sub.name}</h4>
<span class="attendance-percent-badge ${ringClass}">${percent}%</span>
</div>
<div class="attendance-count-box">
<span>${sub.attended}</span>
<span class="denominator">/ ${sub.total} classes</span>
</div>
<div class="progress-bar-container mb-3">
<div class="progress-bar" style="width: ${percent}%; background: ${percent >= target ? 'var(--color-success)' : 'var(--color-danger)'}"></div>
</div>
<p class="attendance-verdict" style="font-size: 0.75rem; text-align: left; background: rgba(0,0,0,0.15)">
${simulatorText}
</p>
<div class="attendance-log-buttons">
<button class="btn-log btn-attended" onclick="logClassAttendance('${sub.id}', true)">+ Attended</button>
<button class="btn-log btn-missed" onclick="logClassAttendance('${sub.id}', false)">+ Missed</button>
</div>
<div style="display: flex; justify-content: flex-end; gap: 8px; margin-top: 1rem; border-top: 1px solid var(--border-color); padding-top: 0.5rem;">
<button class="btn-card-action btn-edit-action" onclick="editSubject('${sub.id}')" title="Edit">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>
</button>
<button class="btn-card-action" onclick="deleteSubject('${sub.id}')" title="Delete">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
</button>
</div>
</div>
`;
}).join("");
}
window.logClassAttendance = function(id, attended) {
const idx = state.subjects.findIndex(s => s.id === id);
if (idx !== -1) {
state.subjects[idx].total++;
if (attended) {
state.subjects[idx].attended++;
showToast(`Logged class attended for ${state.subjects[idx].name}!`, "success");
} else {
showToast(`Logged class missed for ${state.subjects[idx].name}.`, "warning");
}
saveState();
renderAttendanceView();
}
};
window.deleteSubject = function(id) {
if (confirm("Deleting this subject will also delete associated assignments. Proceed?")) {
state.subjects = state.subjects.filter(s => s.id !== id);
// Clean assignments tied to subject
state.assignments = state.assignments.filter(a => a.subjectId !== id);
saveState();
showToast("Subject deleted.", "warning");
renderAttendanceView();
}
};
window.editSubject = function(id) {
const sub = state.subjects.find(s => s.id === id);
if (sub) {
openModal("subject", sub);
}
};
// --- 4. STUDY PLANNER VIEW RENDER ---
function renderPlannerView() {
const todayStr = new Date().toDateString();
// Filter today's tasks
const todaysTasks = state.planner.filter(t => t.dateCreated === todayStr || !t.isCompleted);
// Count variables
const completedTasksCount = todaysTasks.filter(t => t.isCompleted).length;
const totalTasksCount = todaysTasks.length;
const percentage = totalTasksCount > 0 ? Math.round((completedTasksCount / totalTasksCount) * 100) : 0;
// Update big circular progress ring
const bigRing = document.getElementById("planner-big-ring");
const bigText = document.getElementById("planner-big-text");
if (bigRing && bigText) {
bigText.textContent = percentage + "%";
// Calculate offset (stroke-dasharray is 314.16)
const offset = 314.16 - (314.16 * percentage) / 100;
bigRing.style.strokeDashoffset = offset;
}
// Update Counts by Priority
document.getElementById("planner-high-count").textContent = todaysTasks.filter(t => t.priority === "high" && !t.isCompleted).length;
document.getElementById("planner-medium-count").textContent = todaysTasks.filter(t => t.priority === "medium" && !t.isCompleted).length;
document.getElementById("planner-low-count").textContent = todaysTasks.filter(t => t.priority === "low" && !t.isCompleted).length;
// Render list
const listElement = document.getElementById("planner-task-list");
if (!listElement) return;
if (todaysTasks.length === 0) {
listElement.innerHTML = `
<div class="empty-state">
<p>No study tasks scheduled. Use the form above to add a task!</p>
</div>
`;
return;
}
// Sort tasks: pending first, then priority weight
const sorted = [...todaysTasks].sort((a, b) => {
if (a.isCompleted !== b.isCompleted) {
return a.isCompleted ? 1 : -1;
}
const weight = { high: 3, medium: 2, low: 1 };
return (weight[b.priority] || 0) - (weight[a.priority] || 0);
});
listElement.innerHTML = sorted.map(t => `
<li class="task-item ${t.isCompleted ? 'completed-task' : ''}" id="task-${t.id}">
<div class="task-item-left">
<div class="checkbox-custom" onclick="togglePlannerTask('${t.id}')">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
</div>
<span class="task-item-text">${t.title}</span>
</div>
<div style="display: flex; align-items: center; gap: 8px;">
<span class="task-prio-dot ${t.priority}" title="${t.priority} priority"></span>
<button class="btn-card-action" onclick="deletePlannerTask('${t.id}')" title="Delete">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
</button>
</div>
</li>
`).join("");
}
window.togglePlannerTask = function(id) {
const idx = state.planner.findIndex(t => t.id === id);
if (idx !== -1) {
state.planner[idx].isCompleted = !state.planner[idx].isCompleted;
saveState();
renderPlannerView();
}
};
window.deletePlannerTask = function(id) {
state.planner = state.planner.filter(t => t.id !== id);
saveState();
renderPlannerView();
};
function clearCompletedTasks() {
const completedCount = state.planner.filter(t => t.isCompleted).length;
if (completedCount > 0) {
state.planner = state.planner.filter(t => !t.isCompleted);
saveState();
showToast("Completed tasks cleared.", "info");
renderPlannerView();
} else {
showToast("No completed tasks to clear.", "info");
}
}
// --- 5. NOTES SECTION VIEW RENDER ---
let activeNoteSubjectFilter = "all";
let noteSearchQuery = "";
function renderNotesView() {
const grid = document.getElementById("notes-grid");
if (!grid) return;
// Filter notes
let list = [...state.notes];
if (noteSearchQuery) {
list = list.filter(n =>
n.title.toLowerCase().includes(noteSearchQuery) ||
n.subject.toLowerCase().includes(noteSearchQuery) ||
n.content.toLowerCase().includes(noteSearchQuery)
);
}
if (activeNoteSubjectFilter !== "all") {
list = list.filter(n => n.subject.toLowerCase() === activeNoteSubjectFilter.toLowerCase());
}
// Render Filters Row dynamically based on current unique subject tags
const filterContainer = document.getElementById("note-subject-filters");
if (filterContainer) {
const uniqueSubjects = ["All", ...new Set(state.notes.map(n => n.subject.trim()))];
filterContainer.innerHTML = uniqueSubjects.map(sub => {
const key = sub.toLowerCase();
const activeKey = activeNoteSubjectFilter.toLowerCase();
const isActive = key === activeKey;
return `
<button class="filter-btn ${isActive ? 'active' : ''}" onclick="filterNotesBySubject('${key}')">
${sub}
</button>
`;
}).join("");
}
if (list.length === 0) {
grid.innerHTML = `
<div class="empty-state card" style="grid-column: 1 / -1;">
<h3>No notes found</h3>
<p>Try searching for another topic or create a new note.</p>
</div>
`;
return;
}
grid.innerHTML = list.map(n => {
return `
<div class="card note-card" id="note-${n.id}">
<div class="note-card-header">
<h4 class="note-card-title">${n.title}</h4>
<span class="subject-tag">${n.subject}</span>
</div>
<div class="note-card-body">${escapeHTML(n.content)}</div>
<div class="note-card-footer">
<span>${n.dateCreated}</span>
<div style="display: flex; gap: 4px;">
<button class="btn-card-action btn-edit-action" onclick="editNote('${n.id}')" title="Edit">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>
</button>
<button class="btn-card-action" onclick="deleteNote('${n.id}')" title="Delete">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
</button>
</div>
</div>
</div>
`;
}).join("");
}
window.filterNotesBySubject = function(subjectKey) {
activeNoteSubjectFilter = subjectKey;
renderNotesView();
};
window.deleteNote = function(id) {
if (confirm("Are you sure you want to delete this note?")) {
state.notes = state.notes.filter(n => n.id !== id);
saveState();
showToast("Note deleted.", "warning");
renderNotesView();
}
};
window.editNote = function(id) {
const note = state.notes.find(n => n.id === id);
if (note) {
openModal("note", note);
}
};
function initNotesSearch() {
const searchInput = document.getElementById("search-notes");
if (searchInput) {
searchInput.addEventListener("input", (e) => {
noteSearchQuery = e.target.value.toLowerCase().trim();
renderNotesView();
});
}
}
// --- MODAL HANDLING & DIALOG FORM SUBMISSIONS ---
function openModal(modalType, editData = null) {
const backdrop = document.getElementById(`modal-${modalType}`);
if (!backdrop) return;
backdrop.classList.add("active");
// Clear / setup inputs
if (modalType === "subject") {
const titleEl = document.getElementById("subject-modal-title");
const idInput = document.getElementById("input-subject-id");
const nameInput = document.getElementById("input-subject-name");
const attendedInput = document.getElementById("input-subject-attended");
const totalInput = document.getElementById("input-subject-total");
if (editData) {
titleEl.textContent = "Edit Subject";