Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
1538 lines (1306 loc) · 52.4 KB
/
Copy pathcontent.js
File metadata and controls
1538 lines (1306 loc) · 52.4 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
(function () {
'use strict';
const PATHNAME = window.location.pathname;
const IS_FEEDBACK_PAGE = /\/Student\/(?:CourseFeedback|FeedBackQuestions|Feedback|FeedBack)/i.test(PATHNAME);
const IS_MARKS_PAGE = /\/Student\/StudentMarks/i.test(PATHNAME);
const IS_TRANSCRIPT_PAGE = /\/Student\/Transcript/i.test(PATHNAME);
const IS_ATTENDANCE_PAGE = /\/Student\/(?:StudentAttendance|Attendance)/i.test(PATHNAME);
const IS_PORTAL_PAGE = /flexstudent\.nu\.edu\.pk/i.test(window.location.hostname);
const DARK_STYLE_ID = 'proflex-dark-style';
const DARK_OVERLAY_ID = 'proflex-dark-overlay';
const THEME_STORAGE_KEY = 'proflex-theme';
const EXPECTED_MARKS_STORAGE_KEY = 'proflex-expected-marks-v1';
const TRANSCRIPT_GPA_STORAGE_KEY = 'proflex-transcript-gpa-v1';
// feature flags (defaults true)
let featureFeedbackEnabled = true;
let featureMarksEnabled = true;
let featureTranscriptEnabled = true;
let featureAttendanceEnabled = true;
// Session keeper is disabled by default; enable later if needed
let featureSessionEnabled = false;
let featureThemeEnabled = true;
let currentTheme = 'light';
let themeToggleButton = null;
let _proflex_session_timer = null;
// Define constants used by feature pages (must be before any initialization callbacks)
const GRADE_SCALE = {
'A': 4,
'A-': 3.67,
'B+': 3.33,
'B': 3,
'B-': 2.67,
'C+': 2.33,
'C': 2,
'C-': 1.67,
'D+': 1.33,
'D': 1,
'F': 0,
'I': 0,
'S': 0,
};
const FEEDBACK_OPTIONS = [
{ label: 'Strongly Agree', index: 0 },
{ label: 'Agree', index: 1 },
{ label: 'Uncertain', index: 2 },
{ label: 'Dissatisfied', index: 3 },
{ label: 'Strongly Disagree', index: 4 },
];
// Create root container for all ProFlex UI elements (must be before any initialization)
const ROOT_ID = 'proflex-root';
const root = document.createElement('div');
root.id = ROOT_ID;
if (!document.getElementById(ROOT_ID)) {
(document.body || document.documentElement).appendChild(root);
}
// Apply theme immediately to prevent white flash
const storedTheme = localStorage.getItem(THEME_STORAGE_KEY);
if (storedTheme === 'dark') {
// Hide body until styles are applied
document.documentElement.style.backgroundColor = '#0c1320';
document.documentElement.style.color = '#e5eefc';
if (document.body) {
document.body.style.backgroundColor = '#0c1320';
document.body.style.color = '#e5eefc';
}
document.body.classList.add('proflex-dark');
// Inject dark mode styles immediately to prevent flash
if (!document.getElementById(DARK_STYLE_ID)) {
const style = document.createElement('style');
style.id = DARK_STYLE_ID;
style.textContent = `
html,
html.proflex-dark,
body,
body.proflex-dark {
background-color: #0c1320 !important;
color: #e5eefc !important;
}
body.proflex-dark,
body.proflex-dark div:not(.progress-bar),
body.proflex-dark section,
body.proflex-dark header,
body.proflex-dark main,
body.proflex-dark footer,
body.proflex-dark table,
body.proflex-dark tbody,
body.proflex-dark tr,
body.proflex-dark td,
body.proflex-dark th,
body.proflex-dark input,
body.proflex-dark select,
body.proflex-dark textarea,
body.proflex-dark .card,
body.proflex-dark .panel,
body.proflex-dark .panel-body {
background-color: #0c1320 !important;
color: #e5eefc !important;
border-color: #253247 !important;
}
`;
document.head.appendChild(style);
}
}
// Initialize dark mode on all portal pages
// Defer initialization until we read stored feature toggles from extension storage
function initExtensionAfterSettings() {
if (IS_PORTAL_PAGE) {
currentTheme = readInitialTheme();
if (featureThemeEnabled) {
applyTheme(currentTheme);
themeToggleButton = createThemeToggleButton();
}
// session keeper is not started automatically to avoid server-side session issues
// call `initSessionKeeper()` manually from the popup or dev console if needed
}
// Root container is already created at top level, just initialize features
if (IS_FEEDBACK_PAGE && featureFeedbackEnabled) {
initFeedbackPage();
}
if (IS_MARKS_PAGE && featureMarksEnabled) {
initMarksPage();
}
if (IS_TRANSCRIPT_PAGE && featureTranscriptEnabled) {
initTranscriptPage();
}
if (IS_ATTENDANCE_PAGE && featureAttendanceEnabled) {
initAttendanceHelper();
}
}
// Read saved feature toggles (from extension popup) if available
if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
chrome.storage.local.get({
feature_feedback: true,
feature_marks: true,
feature_transcript: true,
feature_attendance: true,
feature_theme: true,
}, (items) => {
featureFeedbackEnabled = !!items.feature_feedback;
featureMarksEnabled = !!items.feature_marks;
featureTranscriptEnabled = !!items.feature_transcript;
featureAttendanceEnabled = !!items.feature_attendance;
featureThemeEnabled = !!items.feature_theme;
initExtensionAfterSettings();
});
} else {
initExtensionAfterSettings();
}
// React to runtime toggle changes so popup toggles affect active pages
if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.onChanged) {
chrome.storage.onChanged.addListener((changes, area) => {
if (area !== 'local') return;
if (changes.feature_feedback) {
featureFeedbackEnabled = !!changes.feature_feedback.newValue;
if (featureFeedbackEnabled) {
try { initFeedbackPage(); } catch (e) { console.warn('[ProFlex] enable feedback failed', e); }
} else {
// remove feedback elements
const fab = document.getElementById('proflex-fab');
const panel = document.getElementById('proflex-panel');
if (fab) fab.remove();
if (panel) panel.remove();
}
}
if (changes.feature_marks) {
featureMarksEnabled = !!changes.feature_marks.newValue;
const summary = document.getElementById('proflex-marks-summary');
if (!featureMarksEnabled && summary) {
summary.remove();
}
if (featureMarksEnabled) {
try { initMarksPage(); } catch (e) { console.warn('[ProFlex] enable marks failed', e); }
}
}
if (changes.feature_transcript) {
featureTranscriptEnabled = !!changes.feature_transcript.newValue;
const card = document.getElementById('proflex-gpa-card');
if (!featureTranscriptEnabled && card) card.remove();
if (featureTranscriptEnabled) {
try { initTranscriptPage(); } catch (e) { console.warn('[ProFlex] enable transcript failed', e); }
}
}
if (changes.feature_theme) {
featureThemeEnabled = !!changes.feature_theme.newValue;
if (!featureThemeEnabled) {
// remove theme control if present
const tbtn = document.getElementById('proflex-theme-toggle');
if (tbtn) tbtn.remove();
} else {
if (!document.getElementById('proflex-theme-toggle')) {
themeToggleButton = createThemeToggleButton();
syncThemeToggleState();
}
}
}
});
}
// Initialize feature-specific functionality only on designated pages
if (document.getElementById(ROOT_ID)) {
// Root already exists, initialization was already done
} else if (IS_FEEDBACK_PAGE || IS_MARKS_PAGE || IS_TRANSCRIPT_PAGE) {
// Initialize for designated pages
if (IS_FEEDBACK_PAGE) {
initFeedbackPage();
}
if (IS_MARKS_PAGE) {
initMarksPage();
}
if (IS_TRANSCRIPT_PAGE) {
initTranscriptPage();
}
}
function readInitialTheme() {
const storedTheme = localStorage.getItem(THEME_STORAGE_KEY);
if (storedTheme === 'dark' || storedTheme === 'light') {
return storedTheme;
}
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function applyTheme(nextTheme) {
currentTheme = nextTheme === 'dark' ? 'dark' : 'light';
localStorage.setItem(THEME_STORAGE_KEY, currentTheme);
if (currentTheme === 'dark') {
enableDarkModeChromeStyle();
document.body.classList.add('proflex-dark');
document.body.classList.remove('proflex-light');
} else {
disableDarkModeChromeStyle();
document.body.classList.remove('proflex-dark');
document.body.classList.add('proflex-light');
}
if (themeToggleButton) {
syncThemeToggleState();
}
}
function enableDarkModeChromeStyle() {
if (!document.getElementById(DARK_STYLE_ID)) {
const style = document.createElement('style');
style.id = DARK_STYLE_ID;
style.textContent = `
body.proflex-dark,
body.proflex-dark div:not(.progress-bar),
body.proflex-dark section,
body.proflex-dark header,
body.proflex-dark main,
body.proflex-dark footer,
body.proflex-dark table,
body.proflex-dark tbody,
body.proflex-dark tr,
body.proflex-dark td,
body.proflex-dark th,
body.proflex-dark input,
body.proflex-dark select,
body.proflex-dark textarea,
body.proflex-dark .card,
body.proflex-dark .panel,
body.proflex-dark .panel-body {
background-color: #0c1320 !important;
color: #e5eefc !important;
border-color: #253247 !important;
}
body.proflex-dark a { color: #bb86fc !important; }
body.proflex-dark .btn { background-color: #333 !important; color: #fff !important; }
`;
document.head.appendChild(style);
}
if (!document.getElementById(DARK_OVERLAY_ID)) {
const overlay = document.createElement('div');
overlay.id = DARK_OVERLAY_ID;
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '300px';
overlay.style.height = '80px';
overlay.style.backgroundColor = '#000';
overlay.style.zIndex = '9999';
overlay.style.pointerEvents = 'none';
document.body.appendChild(overlay);
}
}
/* Attendance Helper Module ------------------------------------------------- */
function initAttendanceHelper() {
try {
const portletBody = document.querySelector('.m-portlet__body');
if (!portletBody) return;
const panes = Array.from(portletBody.querySelectorAll('.tab-content .tab-pane'));
panes.forEach((pane) => {
try {
renderAttendanceForPane(pane);
} catch (e) {
console.warn('[ProFlex][Attendance] render failed for pane', e);
}
});
// Re-run when tab-content changes
const tabContent = portletBody.querySelector('.tab-content');
if (tabContent) {
const observer = new MutationObserver(() => {
panes.forEach((pane) => renderAttendanceForPane(pane));
});
observer.observe(tabContent, { childList: true, subtree: true });
}
} catch (err) {
console.warn('[ProFlex][Attendance] init failed', err);
}
}
function renderAttendanceForPane(pane) {
if (!pane) return;
// Avoid duplicate widget
if (pane.querySelector('.proflex-attendance-helper')) return;
const titleEl = pane.querySelector('h5');
const courseTitle = titleEl ? normalizeText(titleEl.textContent) : 'Course';
const table = pane.querySelector('table');
if (!table) return;
// Find Presence column index by header text
const headers = Array.from(table.querySelectorAll('thead th')).map((th) => normalizeText(th.textContent));
let presenceIndex = headers.findIndex((h) => /presence|status|attend/i.test(h));
if (presenceIndex === -1) {
// fallback to last column
presenceIndex = Math.max(0, headers.length - 1);
}
const rows = Array.from(table.querySelectorAll('tbody tr'));
let absents = 0;
rows.forEach((row) => {
const cells = Array.from(row.children).map((c) => normalizeText(c.textContent));
const presence = cells[presenceIndex] || '';
if (/^A$/i.test(presence) || /absent/i.test(presence)) {
absents += 1;
}
});
const totalClasses = rows.length;
// Build compact widget showing absence totals only
const widget = document.createElement('div');
widget.className = 'proflex-attendance-helper';
widget.innerHTML = `
<div class="proflex-attendance-body">
<div class="proflex-attendance-absents"><span class="proflex-attendance-label">Absents</span><span class="proflex-attendance-value">${absents}</span></div>
<div class="proflex-attendance-total"><span class="proflex-attendance-label">Total Classes</span><span class="proflex-attendance-value">${totalClasses}</span></div>
</div>
`;
// Insert directly before the table so it appears near course attendance
const tableParent = table.parentElement || pane;
tableParent.insertBefore(widget, table);
styleAttendanceProgressBar(pane);
}
function styleAttendanceProgressBar(pane) {
if (!pane) return;
const progressBar = pane.querySelector('.progress-bar');
if (!progressBar) return;
const valueMatch = (progressBar.getAttribute('aria-valuenow') || normalizeText(progressBar.textContent)).match(/\d+(?:\.\d+)?/);
if (!valueMatch) return;
const value = parseFloat(valueMatch[0]);
if (!Number.isFinite(value)) return;
const isPassing = value >= 80;
progressBar.style.backgroundColor = isPassing ? '#16a34a' : '#dc2626';
progressBar.style.color = '#ffffff';
progressBar.style.borderColor = isPassing ? '#16a34a' : '#dc2626';
}
/* Session Keeper Module --------------------------------------------------- */
function initSessionKeeper() {}
function startSessionKeeper() {}
function stopSessionKeeper() {}
function disableDarkModeChromeStyle() {
const overlay = document.getElementById(DARK_OVERLAY_ID);
if (overlay) {
overlay.remove();
}
}
function toggleTheme() {
applyTheme(currentTheme === 'dark' ? 'light' : 'dark');
}
function createThemeToggleButton() {
const wrapper = document.createElement('div');
wrapper.id = 'proflex-theme-toggle';
wrapper.className = 'proflex-theme-toggle';
wrapper.innerHTML = `
<span class="proflex-theme-label proflex-theme-label-dark" data-role="theme-dark-label" aria-hidden="true">${darkModeIcon()}</span>
<label class="proflex-theme-switch-wrap" for="proflex-theme-switch">
<input id="proflex-theme-switch" type="checkbox" class="proflex-theme-switch" aria-label="Toggle between dark and light mode">
<span class="proflex-theme-switch-track" aria-hidden="true">
<span class="proflex-theme-switch-thumb"></span>
</span>
</label>
<span class="proflex-theme-label proflex-theme-label-light" data-role="theme-light-label" aria-hidden="true">${lightModeIcon()}</span>
`;
const switchInput = wrapper.querySelector('#proflex-theme-switch');
switchInput.checked = readInitialTheme() === 'light';
switchInput.addEventListener('change', () => {
applyTheme(switchInput.checked ? 'light' : 'dark');
});
(document.body || document.documentElement).appendChild(wrapper);
syncThemeToggleState();
return wrapper;
}
function syncThemeToggleState() {
if (!themeToggleButton) {
return;
}
const savedTheme = readInitialTheme();
if (savedTheme === 'dark' || savedTheme === 'light') {
currentTheme = savedTheme;
}
const switchInput = themeToggleButton.querySelector('#proflex-theme-switch');
if (switchInput) {
switchInput.checked = currentTheme === 'light';
}
const darkLabel = themeToggleButton.querySelector('[data-role="theme-dark-label"]');
const lightLabel = themeToggleButton.querySelector('[data-role="theme-light-label"]');
if (darkLabel) {
darkLabel.classList.toggle('proflex-theme-label-active', currentTheme === 'dark');
}
if (lightLabel) {
lightLabel.classList.toggle('proflex-theme-label-active', currentTheme === 'light');
}
themeToggleButton.setAttribute('aria-label', currentTheme === 'dark' ? 'Toggle to light mode' : 'Toggle to dark mode');
themeToggleButton.title = currentTheme === 'dark' ? 'Toggle to light mode' : 'Toggle to dark mode';
}
function initFeedbackPage() {
if (document.getElementById('proflex-fab')) {
return;
}
const fab = document.createElement('button');
fab.id = 'proflex-fab';
fab.type = 'button';
fab.title = 'Auto Fill Feedback';
fab.setAttribute('aria-label', 'Auto Fill Feedback');
fab.textContent = 'Feedback Filler';
const panel = document.createElement('div');
panel.id = 'proflex-panel';
panel.className = 'proflex-hidden';
const header = document.createElement('div');
header.className = 'proflex-panel-header';
header.innerHTML = `
<div class="proflex-panel-title">
<span class="proflex-panel-mark">✦</span>
<span>Auto Fill Feedback</span>
</div>
<button id="proflex-minimize" type="button" class="proflex-panel-close" title="Minimize" aria-label="Minimize">−</button>
`;
const options = document.createElement('div');
options.id = 'proflex-options';
FEEDBACK_OPTIONS.forEach(({ label, index }) => {
options.appendChild(createFeedbackOptionButton(label, false, () => fillFeedback(index, false, label)));
});
options.appendChild(createFeedbackOptionButton('Randomize', true, () => fillFeedback(null, true, 'Randomize')));
const status = document.createElement('div');
status.id = 'proflex-status';
status.textContent = 'Pick an option to fill.';
panel.appendChild(header);
panel.appendChild(options);
panel.appendChild(status);
root.appendChild(fab);
root.appendChild(panel);
let isOpen = false;
function openPanel() {
isOpen = true;
panel.classList.remove('proflex-hidden');
panel.classList.add('proflex-visible');
fab.title = 'Minimize panel';
}
function closePanel() {
isOpen = false;
panel.classList.remove('proflex-visible');
panel.classList.add('proflex-hidden');
fab.title = 'Auto Fill Feedback';
}
fab.addEventListener('click', () => {
if (isOpen) {
closePanel();
} else {
openPanel();
}
});
panel.querySelector('#proflex-minimize').addEventListener('click', closePanel);
function createFeedbackOptionButton(label, isRandom, onClick) {
const button = document.createElement('button');
button.type = 'button';
button.className = isRandom ? 'proflex-option proflex-option-random' : 'proflex-option';
button.dataset.label = label;
const dot = document.createElement('span');
dot.className = 'proflex-dot';
const text = document.createElement('span');
text.className = 'proflex-option-label';
text.textContent = isRandom ? 'Randomize' : label;
button.appendChild(dot);
button.appendChild(text);
button.addEventListener('click', onClick);
return button;
}
function setActiveButton(activeLabel) {
options.querySelectorAll('.proflex-option').forEach((button) => {
button.classList.toggle('proflex-active', button.dataset.label === activeLabel);
});
}
function setStatus(message, ok) {
status.textContent = message;
status.className = ok ? 'proflex-ok' : '';
}
function fillFeedback(fixedIndex, randomize, label) {
setActiveButton(label);
setStatus('Filling...', false);
const radios = Array.from(document.querySelectorAll('input[type="radio"]'));
if (radios.length === 0) {
setStatus('No radio inputs found.', false);
console.warn('[FAF] No radio inputs found on this page.');
return;
}
const groups = new Map();
const order = [];
radios.forEach((radio) => {
if (!radio.name) {
return;
}
if (!groups.has(radio.name)) {
groups.set(radio.name, []);
order.push(radio.name);
}
groups.get(radio.name).push(radio);
});
let delay = 0;
order.forEach((name) => {
const group = groups.get(name);
if (!group || group.length === 0) {
return;
}
const index = randomize ? Math.floor(Math.random() * group.length) : Math.min(fixedIndex, group.length - 1);
const radio = group[index];
setTimeout(() => {
try {
const labelElement = radio.closest('label');
if (labelElement) {
labelElement.click();
} else {
radio.checked = true;
radio.dispatchEvent(new Event('change', { bubbles: true }));
}
console.log(`[FAF] Filled "${name}" → ${label}`);
} catch (error) {
console.error(`[FAF] Error on group "${name}":`, error);
}
}, delay);
delay += 10 + Math.floor(Math.random() * 21);
});
setTimeout(() => {
setStatus(`✓ ${order.length} question(s) filled.`, true);
console.log(`[FAF] Done — ${order.length} group(s) filled with: ${label}`);
}, delay + 150);
}
}
function initMarksPage() {
const portletBody = document.querySelector('.m-portlet__body');
if (!portletBody) {
return;
}
const tabContent = portletBody.querySelector('.tab-content');
if (!tabContent) {
return;
}
if (document.getElementById('proflex-marks-summary')) {
return;
}
const summaryCard = document.createElement('section');
summaryCard.id = 'proflex-marks-summary';
summaryCard.className = 'proflex-inline-card';
summaryCard.innerHTML = `
<div class="proflex-card-head">
<div>
<div class="proflex-eyebrow">ProFlex Marks</div>
<h3>Grand Total</h3>
</div>
<button type="button" class="proflex-card-action" data-role="refresh-marks">Recalculate</button>
</div>
<div class="proflex-stat-grid">
<div class="proflex-stat">
<span class="proflex-stat-label">Grand total</span>
<strong data-role="marks-value">--</strong>
</div>
<div class="proflex-stat">
<span class="proflex-stat-label">Coverage</span>
<strong data-role="marks-meta">--</strong>
</div>
</div>
<p class="proflex-note">Based on the visible totals in the active course tab.</p>
<div class="proflex-marks-editor" data-role="marks-editor" hidden>
<div class="proflex-marks-editor-head">
<div>
<div class="proflex-eyebrow">Expected marks</div>
<h4>Fill missing obtained marks</h4>
</div>
<div class="proflex-marks-editor-actions">
<button type="button" class="proflex-card-action" data-role="apply-expected-marks">Recalculate</button>
<button type="button" class="proflex-card-action proflex-card-action-secondary" data-role="reset-expected-marks">Reset</button>
<button type="button" class="proflex-card-action proflex-card-action-secondary" data-role="reset-all-expected-marks">Reset All</button>
</div>
</div>
<p class="proflex-note">Only rows with hyphens are editable here. Enter the expected obtained marks for each missing row to include it in your projection.</p>
<div class="proflex-table-wrap proflex-marks-editor-wrap">
<table class="proflex-gpa-table proflex-marks-editor-table">
<thead>
<tr>
<th>Section</th>
<th class="proflex-cell-center">Row weightage</th>
<th class="proflex-cell-center">Total marks</th>
<th class="proflex-cell-center">Expected obtained</th>
</tr>
</thead>
<tbody data-role="marks-editor-rows"></tbody>
</table>
</div>
</div>
`;
portletBody.insertBefore(summaryCard, tabContent);
const refreshButton = summaryCard.querySelector('[data-role="refresh-marks"]');
const applyExpectedButton = summaryCard.querySelector('[data-role="apply-expected-marks"]');
const resetExpectedButton = summaryCard.querySelector('[data-role="reset-expected-marks"]');
const resetAllExpectedButton = summaryCard.querySelector('[data-role="reset-all-expected-marks"]');
const editorWrap = summaryCard.querySelector('[data-role="marks-editor"]');
const editorRows = summaryCard.querySelector('[data-role="marks-editor-rows"]');
const expectedMarksStore = loadExpectedMarksStore();
const scheduleRefresh = createDebounced(() => renderMarksSummary(summaryCard, tabContent, expectedMarksStore), 40);
const updateProjection = () => updateMarksProjection(summaryCard, tabContent, expectedMarksStore);
refreshButton.addEventListener('click', () => renderMarksSummary(summaryCard, tabContent, expectedMarksStore));
applyExpectedButton.addEventListener('click', () => updateProjection());
resetExpectedButton.addEventListener('click', () => {
const data = computeVisibleMarks(tabContent, expectedMarksStore);
if (!data || data.missingRows.length === 0) {
return;
}
summaryCard.querySelectorAll('[data-role="expected-obtained"]').forEach((input) => {
input.value = '';
});
data.missingRows.forEach((row) => {
delete expectedMarksStore[row.key];
});
saveExpectedMarksStore(expectedMarksStore);
updateProjection();
renderMarksSummary(summaryCard, tabContent, expectedMarksStore);
});
resetAllExpectedButton.addEventListener('click', () => {
summaryCard.querySelectorAll('[data-role="expected-obtained"]').forEach((input) => {
input.value = '';
});
Object.keys(expectedMarksStore).forEach((key) => {
delete expectedMarksStore[key];
});
saveExpectedMarksStore(expectedMarksStore);
updateProjection();
renderMarksSummary(summaryCard, tabContent, expectedMarksStore);
});
summaryCard.addEventListener('input', (event) => {
const input = event.target.closest('[data-role="expected-obtained"]');
if (!input) {
return;
}
const rowKey = input.dataset.rowKey;
if (!rowKey) {
return;
}
if (normalizeText(input.value) === '') {
delete expectedMarksStore[rowKey];
saveExpectedMarksStore(expectedMarksStore);
updateProjection();
return;
}
const maxValue = parseNumber(input.dataset.rowMax || input.max);
const currentValue = parseNumber(input.value);
if (Number.isFinite(currentValue) && Number.isFinite(maxValue)) {
const clampedValue = Math.max(0, Math.min(maxValue, currentValue));
input.value = String(clampedValue);
expectedMarksStore[rowKey] = clampedValue;
} else if (Number.isFinite(currentValue)) {
expectedMarksStore[rowKey] = Math.max(0, currentValue);
}
saveExpectedMarksStore(expectedMarksStore);
updateProjection();
});
portletBody.addEventListener('click', (event) => {
if (event.target.closest('#proflex-marks-summary')) {
return;
}
scheduleRefresh();
}, true);
const observer = new MutationObserver(scheduleRefresh);
observer.observe(tabContent, {
subtree: true,
childList: true,
characterData: true,
attributes: true,
attributeFilter: ['class', 'style', 'aria-expanded'],
});
renderMarksSummary(summaryCard, tabContent, expectedMarksStore);
}
function renderMarksSummary(summaryCard, tabContent, expectedMarksStore) {
const valueElement = summaryCard.querySelector('[data-role="marks-value"]');
const metaElement = summaryCard.querySelector('[data-role="marks-meta"]');
const editorWrap = summaryCard.querySelector('[data-role="marks-editor"]');
const editorRows = summaryCard.querySelector('[data-role="marks-editor-rows"]');
const expectedMarks = readExpectedMarks(summaryCard, expectedMarksStore);
const data = computeVisibleMarks(tabContent, expectedMarksStore);
if (!data) {
valueElement.textContent = '--';
metaElement.textContent = 'No totals found';
editorWrap.hidden = true;
editorRows.innerHTML = '';
return;
}
if (data.missingRows.length > 0) {
editorWrap.hidden = false;
editorRows.innerHTML = data.missingRows.map((row, index) => {
const rowValue = expectedMarks[row.key];
const rowMax = row.totalMarks > 0 ? row.totalMarks : row.weightage;
return `
<tr data-index="${index}">
<td>
<div class="proflex-marks-section-name">${escapeHtml(row.sectionName)}</div>
<div class="proflex-marks-section-detail">${escapeHtml(row.label)}</div>
</td>
<td class="proflex-cell-center">${formatNumber(row.weightage)}</td>
<td class="proflex-cell-center">${formatNumber(row.totalMarks)}</td>
<td class="proflex-cell-center">
<input type="number" min="0" max="${rowMax}" step="0.01" value="${rowValue !== undefined ? escapeHtml(String(rowValue)) : ''}" class="proflex-marks-input" data-role="expected-obtained" data-row-key="${escapeHtml(row.key)}" data-row-total="${escapeHtml(String(row.totalMarks))}" data-row-weightage="${escapeHtml(String(row.weightage))}" data-row-max="${escapeHtml(String(rowMax))}" placeholder="0.00">
</td>
</tr>
`;
}).join('');
} else {
editorWrap.hidden = true;
editorRows.innerHTML = '';
}
updateMarksDisplay(summaryCard, data, expectedMarks, valueElement, metaElement);
}
function updateMarksProjection(summaryCard, tabContent, expectedMarksStore) {
const valueElement = summaryCard.querySelector('[data-role="marks-value"]');
const metaElement = summaryCard.querySelector('[data-role="marks-meta"]');
const data = computeVisibleMarks(tabContent, expectedMarksStore);
if (!data) {
valueElement.textContent = '--';
metaElement.textContent = 'No totals found';
return;
}
updateMarksDisplay(summaryCard, data, readExpectedMarks(summaryCard, expectedMarksStore), valueElement, metaElement);
}
function updateMarksDisplay(summaryCard, data, expectedMarks, valueElement, metaElement) {
const projected = applyExpectedMarks(data, expectedMarks);
const percentage = projected.total ? (projected.obtained / projected.total) * 100 : 0;
valueElement.textContent = `${formatNumber(projected.obtained)} / ${formatNumber(projected.total)}`;
metaElement.textContent = `${projected.sectionCount} section${projected.sectionCount === 1 ? '' : 's'} • ${formatNumber(percentage)}%`;
}
function readExpectedMarks(summaryCard, expectedMarksStore) {
const expectedMarks = { ...(expectedMarksStore || {}) };
summaryCard.querySelectorAll('[data-role="expected-obtained"]').forEach((input) => {
const rowKey = input.dataset.rowKey;
if (!rowKey) {
return;
}
if (normalizeText(input.value) === '') {
delete expectedMarks[rowKey];
return;
}
const value = parseNumber(input.value);
if (Number.isFinite(value)) {
const maxValue = parseNumber(input.dataset.rowMax || input.max);
expectedMarks[rowKey] = Number.isFinite(maxValue)
? Math.max(0, Math.min(maxValue, value))
: Math.max(0, value);
}
});
return expectedMarks;
}
function applyExpectedMarks(data, expectedMarks) {
let obtainedTotal = data.obtained;
let possibleTotal = data.total;
let sectionCount = data.sectionCount;
data.missingRows.forEach((row) => {
const expectedValue = expectedMarks[row.key];
if (!Number.isFinite(expectedValue)) {
return;
}
const rowMax = row.totalMarks > 0 ? row.totalMarks : row.weightage;
const clampedValue = Math.max(0, Math.min(rowMax, expectedValue));
const contribution = row.totalMarks > 0
? (clampedValue / row.totalMarks) * row.weightage
: clampedValue;
obtainedTotal += contribution;
});
return {
obtained: obtainedTotal,
total: possibleTotal,
sectionCount,
};
}
function computeVisibleMarks(tabContent, expectedMarksStore) {
const activePane = tabContent.querySelector('.tab-pane.active') || tabContent.querySelector('.tab-pane');
if (!activePane) {
return null;
}
const paneKey = getPaneStorageKey(activePane);
const tables = Array.from(activePane.querySelectorAll('table'));
let obtainedTotal = 0;
let possibleTotal = 0;
let sectionCount = 0;
const missingRows = [];
const resolvedRowKeys = [];
tables.forEach((table, tableIndex) => {
if (isGrandTotalTable(table)) {
return;
}
const result = extractMarksTableTotal(table);
if (!result) {
return;
}
obtainedTotal += result.obtained;
possibleTotal += result.total;
sectionCount += 1;
const rowState = extractRowStateEntries(table, tableIndex, paneKey);
missingRows.push(...rowState.missingRows);
resolvedRowKeys.push(...rowState.resolvedRowKeys);
});
if (expectedMarksStore && resolvedRowKeys.length > 0) {
let didChange = false;
resolvedRowKeys.forEach((rowKey) => {
if (Object.prototype.hasOwnProperty.call(expectedMarksStore, rowKey)) {
delete expectedMarksStore[rowKey];
didChange = true;
}
});
if (didChange) {
saveExpectedMarksStore(expectedMarksStore);
}
}
if (sectionCount === 0 && missingRows.length === 0) {
return null;
}
return {
obtained: obtainedTotal,
total: possibleTotal,
sectionCount,
missingRows,
};
}
function extractRowStateEntries(table, tableIndex, paneKey) {
const sectionName = normalizeText(table.closest('.card')?.querySelector('.card-header')?.textContent || 'Section');
const rows = Array.from(table.querySelectorAll('tbody tr')).filter((row) => !/total/i.test(normalizeText(row.textContent)));
const missingRows = [];
const resolvedRowKeys = [];
rows.forEach((row, index) => {
const cells = Array.from(row.cells).map((cell) => normalizeText(cell.textContent));
const label = normalizeText(cells[0] || `Row ${index + 1}`);
const rowKey = `${paneKey}::${sectionName}::${tableIndex}::${label}::${index}`;
const obtainedText = cells[2] || '';
if (!/^-$/.test(obtainedText)) {
if (Number.isFinite(parseNumber(obtainedText))) {