Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1800 lines (1603 loc) · 75 KB
/
Copy pathapp.js
File metadata and controls
1800 lines (1603 loc) · 75 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
document.addEventListener('DOMContentLoaded', () => {
// Search Elements
const searchForm = document.getElementById('search-form');
const searchInput = document.getElementById('search-input');
const searchClearBtn = document.getElementById('search-clear-btn');
const sectionSelect = document.getElementById('section-select');
const sortSelect = document.getElementById('sort-select');
const visibleCount = document.getElementById('visible-count');
const totalCount = document.getElementById('total-count');
const statStudents = document.getElementById('stat-students');
const loadingState = document.getElementById('loading-state');
const emptyState = document.getElementById('empty-state');
const leaderboardContainer = document.getElementById('leaderboard-container');
const leaderboardBody = document.getElementById('leaderboard-body');
const paginationContainer = document.getElementById('pagination-container');
const pageSizeSelect = document.getElementById('page-size');
const btnPrev = document.getElementById('btn-prev');
const btnNext = document.getElementById('btn-next');
const pageNumbersContainer = document.getElementById('page-numbers');
// Student Modal Elements
const studentModal = document.getElementById('student-modal');
const studentModalInner = document.getElementById('student-modal-inner');
const studentModalClose = document.getElementById('student-modal-close');
const modalName = document.getElementById('modal-name');
const modalRollBadge = document.getElementById('modal-roll-badge');
const modalSl = document.getElementById('modal-sl');
const modalRoll = document.getElementById('modal-roll');
const modalSection = document.getElementById('modal-section');
const modalDept = document.getElementById('modal-dept');
const modalSession = document.getElementById('modal-session');
const modalSchool = document.getElementById('modal-school');
const modalSscMarks = document.getElementById('modal-ssc-marks');
const modalMarksSection = document.getElementById('modal-marks-section');
const modalMarksTbody = document.getElementById('modal-marks-tbody');
const modalMarksCount = document.getElementById('modal-marks-count');
const modalMarksUnresolved = document.getElementById('modal-marks-unresolved');
const modalCopyBtn = document.getElementById('modal-copy-btn');
// Search Context Banner
const searchContextBanner = document.getElementById('search-context-banner');
// Privacy Policy Elements
const openPrivacyBtn = document.getElementById('open-privacy-btn');
const privacyModal = document.getElementById('privacy-modal');
const privacyModalInner = document.getElementById('privacy-modal-inner');
const privacyModalClose = document.getElementById('privacy-modal-close');
const privacyModalOkBtn = document.getElementById('privacy-modal-ok-btn');
// Welcome / Notice Modal Elements
const welcomeModal = document.getElementById('welcome-modal');
const welcomeModalInner = document.getElementById('welcome-modal-inner');
const welcomeClose = document.getElementById('welcome-close');
// Auth Modal Elements
const authModal = document.getElementById('auth-modal');
const authModalInner = document.getElementById('auth-modal-inner');
const authModalClose = document.getElementById('auth-modal-close');
const authLoginBtn = document.getElementById('auth-login-btn');
// Toast
const toast = document.getElementById('toast');
const toastText = document.getElementById('toast-text');
const AUTH_STORAGE_KEY = 'hscstack_auth_user';
// Theme system — mirrors platform resources/js/lib/useDarkMode.ts:
// same 'theme' localStorage key, same light/dark/system cycle.
// Per-origin storage means this won't sync with hscstack.site;
// both sides just resolve 'system' from the OS preference.
var currentTheme = 'system';
try {
var storedTheme = localStorage.getItem('theme');
if (storedTheme === 'light' || storedTheme === 'dark' || storedTheme === 'system') {
currentTheme = storedTheme;
}
} catch (e) {}
function resolveDark(t) {
if (t === 'system') {
return window.matchMedia('(prefers-color-scheme: dark)').matches;
}
return t === 'dark';
}
function refreshThemeIcon() {
var icon = document.getElementById('rail-theme-icon') || document.getElementById('theme-toggle-icon');
if (icon) {
icon.textContent = currentTheme === 'dark' ? 'dark_mode' : currentTheme === 'light' ? 'light_mode' : 'computer';
}
var btn = document.getElementById('rail-theme-toggle');
if (btn) btn.title = 'Current theme: ' + currentTheme + '. Click to switch.';
refreshAppearanceSegmented();
}
// Platform parity: the Light/Dark/System segmented control in the rail
// footer + drawer pinned footer highlights the active theme.
var SEG_ACTIVE = ['bg-white', 'text-slate-900', 'shadow-sm', 'dark:bg-slate-700', 'dark:text-slate-100'];
var SEG_IDLE = ['text-slate-500', 'hover:text-slate-800', 'dark:text-slate-400', 'dark:hover:text-slate-200'];
function refreshAppearanceSegmented() {
document.querySelectorAll('[data-set-theme]').forEach(function (el) {
var isActive = el.getAttribute('data-set-theme') === currentTheme;
SEG_ACTIVE.forEach(function (c) { el.classList.toggle(c, isActive); });
SEG_IDLE.forEach(function (c) { el.classList.toggle(c, !isActive); });
});
}
function applyTheme() {
var dark = resolveDark(currentTheme);
document.documentElement.classList.toggle('dark', dark);
document.documentElement.style.colorScheme = dark ? 'dark' : 'light';
var themeColor = dark ? '#030712' : '#f8fafc';
var meta = document.querySelector('meta[name="theme-color"]:not([media])');
if (meta) meta.setAttribute('content', themeColor);
var navButton = document.querySelector('meta[name="msapplication-navbutton-color"]');
if (navButton) navButton.setAttribute('content', themeColor);
try {
localStorage.setItem('theme', currentTheme);
} catch (e) {}
refreshThemeIcon();
}
function cycleTheme() {
var order = ['system', 'light', 'dark'];
currentTheme = order[(order.indexOf(currentTheme) + 1) % order.length];
applyTheme();
}
applyTheme();
try {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function () {
if (currentTheme === 'system') applyTheme();
});
window.addEventListener('storage', function (e) {
if (e.key === 'theme' && (e.newValue === 'light' || e.newValue === 'dark' || e.newValue === 'system')) {
currentTheme = e.newValue;
applyTheme();
}
});
} catch (e) {}
/* ================================================================
* Platform shell — vanilla port of resources/js/components/
* navigation/Navigation.tsx (SiteRail/SiteDrawer/SiteBottomNav)
* plus lib/navigation.ts + lib/useBottomNavCustomization.ts.
*
* All links are absolute (https://hscstack.site/...) so the rail,
* drawer and bottom bar behave like the platform itself.
* Active states resolve against VIRTUAL_PATH: this directory is
* reached via More From Us (/projects), so that row renders
* active — the user feels they never left the site.
* ================================================================ */
var PLATFORM_ORIGIN = 'https://hscstack.site';
var VIRTUAL_PATH = '/projects/rgc-students';
var NAV_SPEC_CACHE_KEY = 'hscstack_nav_spec_v1';
var RAIL_KEY = 'rail_collapsed';
// Baked-in fallback = live platform spec (resources/js/lib/navigation.ts).
// Refreshed at runtime from GET /api/navigation when available.
var DEFAULT_NAV_SPEC = {
primary: [
{ label: 'Home', href: '/', icon: 'home', showInBottom: true },
{ label: 'Tracker', href: '/tracker', icon: 'timer', showInBottom: true },
{ label: 'People', href: '/peers', icon: 'group', showInBottom: true },
{ label: 'Forum', href: '/forum', icon: 'forum', showInBottom: true },
{ label: 'Chat', href: '/chat', icon: 'chat', showInBottom: true },
{ label: 'Blogs', href: '/blogs', icon: 'menu_book', showInBottom: false },
{ label: 'AI', href: '/ai', icon: 'smart_toy', showInBottom: false }
],
overflow: [
{ label: 'Support Center', href: '/support', icon: 'help', showInBottom: false },
{ label: 'Donate', href: '/donate', icon: 'volunteer_activism', showInBottom: false }
]
};
var currentNavSpec = DEFAULT_NAV_SPEC;
function absUrl(href) {
return PLATFORM_ORIGIN + href;
}
// Platform preferredHomeHref: users with an SSC preference land on /ssc.
function homeUrl() {
try {
if (localStorage.getItem('preferred_course') === 'ssc') return PLATFORM_ORIGIN + '/ssc';
} catch (e) {}
return PLATFORM_ORIGIN;
}
function syncHomeLinks() {
var url = homeUrl();
document.querySelectorAll('[data-home-link]').forEach(function (a) {
a.setAttribute('href', url);
});
}
function allNavItems(spec) {
spec = spec || currentNavSpec;
return (spec.primary || []).concat(spec.overflow || []);
}
function sanitizeNavItem(raw) {
if (!raw || typeof raw.label !== 'string' || typeof raw.href !== 'string' || typeof raw.icon !== 'string') {
return null;
}
if (raw.href.charAt(0) !== '/' || raw.href.indexOf('//') === 0) return null;
if (!/^[a-z0-9_]+$/.test(raw.icon)) return null;
return { label: raw.label.slice(0, 32), href: raw.href.slice(0, 64), icon: raw.icon, showInBottom: raw.showInBottom === true };
}
function sanitizeNavSpec(raw) {
if (!raw || !Array.isArray(raw.primary) || !Array.isArray(raw.overflow)) return null;
var primary = raw.primary.map(sanitizeNavItem).filter(Boolean);
var overflow = raw.overflow.map(sanitizeNavItem).filter(Boolean);
if (primary.length === 0) return null;
return { primary: primary, overflow: overflow };
}
function loadCachedNavSpec() {
try {
var raw = localStorage.getItem(NAV_SPEC_CACHE_KEY);
if (!raw) return null;
return sanitizeNavSpec(JSON.parse(raw));
} catch (e) {
return null;
}
}
// Live nav sync: same channel as the auth check (same-site + CORS-open),
// so sidebar items follow the platform with zero redeploys.
var navRefreshInFlight = false;
function refreshNavSpec() {
if (navRefreshInFlight) return;
navRefreshInFlight = true;
var controller = null;
try {
controller = new AbortController();
} catch (e) {}
var timeoutId = null;
if (controller) {
timeoutId = setTimeout(function () { try { controller.abort(); } catch (e) {} }, 2500);
}
fetch(PLATFORM_ORIGIN + '/api/navigation', controller ? { signal: controller.signal } : {})
.then(function (res) {
if (!res.ok) throw new Error('bad status');
return res.json();
})
.then(function (data) {
var spec = sanitizeNavSpec(data);
if (!spec) return;
if (JSON.stringify(spec) === JSON.stringify(currentNavSpec)) return;
currentNavSpec = spec;
try {
localStorage.setItem(NAV_SPEC_CACHE_KEY, JSON.stringify(spec));
} catch (e) {}
renderAllNav();
})
.catch(function () {})
.then(function () {
navRefreshInFlight = false;
if (timeoutId) clearTimeout(timeoutId);
});
}
// Platform rail label rules (Navigation.tsx): collapsed shortens
// Support Center; expanded uses Global Chat for /chat.
function collapsedLabel(item) {
return item.href === '/support' ? 'Support' : item.label;
}
function expandedLabel(item) {
return item.href === '/chat' ? 'Global Chat' : item.label;
}
var RAIL_ROW_BASE = 'group flex h-10 items-center gap-3 rounded-[10px] px-3 text-[13px] font-medium tracking-tight transition-colors duration-150 ';
var RAIL_ICON_BASE = 'material-symbols-rounded shrink-0 text-[22px] transition-colors duration-150 ';
var RAIL_IDLE = 'text-slate-600 hover:bg-slate-100/80 hover:text-slate-900 dark:text-slate-400 dark:hover:bg-slate-800/70 dark:hover:text-slate-100';
var RAIL_ICON_IDLE = 'text-slate-500 group-hover:text-slate-700 dark:text-slate-500 dark:group-hover:text-slate-300';
function renderRailNav() {
var items = allNavItems();
var col = document.getElementById('rail-nav-collapsed');
if (col) {
col.innerHTML = items.map(function (item) {
var homeAttr = item.href === '/' ? ' data-home-link' : '';
return '<a href="' + absUrl(item.href) + '"' + homeAttr + ' title="' + escapeHTML(item.label) + '" class="group flex h-[60px] w-full flex-col items-center justify-center rounded-xl px-1 text-center text-slate-600 transition-colors duration-150 hover:bg-slate-100/80 hover:text-slate-900 dark:text-slate-400 dark:hover:bg-slate-800/70 dark:hover:text-slate-100">' +
'<span class="' + RAIL_ICON_BASE + 'text-slate-500 group-hover:text-slate-700 dark:text-slate-500 dark:group-hover:text-slate-300">' + item.icon + '</span>' +
'<span class="mt-1 max-w-[64px] truncate text-[10px] font-medium leading-tight">' + escapeHTML(collapsedLabel(item)) + '</span></a>';
}).join('');
}
var exp = document.getElementById('rail-nav-expanded');
if (exp) {
var rows = items.map(function (item) {
var homeAttr = item.href === '/' ? ' data-home-link' : '';
return '<a href="' + absUrl(item.href) + '"' + homeAttr + ' class="' + RAIL_ROW_BASE + RAIL_IDLE + '">' +
'<span class="' + RAIL_ICON_BASE + RAIL_ICON_IDLE + '">' + item.icon + '</span>' +
'<span class="truncate">' + escapeHTML(expandedLabel(item)) + '</span></a>';
}).join('');
var platformSection = exp.querySelector('[data-platform-section]');
if (platformSection) {
exp.innerHTML = rows;
exp.appendChild(platformSection);
} else {
exp.innerHTML = rows;
}
}
syncHomeLinks();
}
function renderBottomNav() {
var host = document.getElementById('bottom-nav-items');
if (!host) return;
// Live platform rule: primary items flagged showInBottom (static, no account tab).
var items = (currentNavSpec.primary || []).filter(function (i) { return i.showInBottom; });
host.innerHTML = items.map(function (item) {
var active = VIRTUAL_PATH.indexOf(item.href) === 0 && item.href !== '/';
return '' +
'<a href="' + absUrl(item.href) + '"' + (item.href === '/' ? ' data-home-link' : '') + ' class="flex min-w-0 flex-1 flex-col items-center gap-1 rounded-xl px-2 py-2 transition-all duration-150 ease-out ' + (active ? 'text-slate-900 dark:text-white' : 'text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200') + '">' +
'<span class="material-symbols-rounded shrink-0 transition-transform duration-150 text-[26px] ' + (active ? 'scale-[1.02] text-slate-900 dark:text-white' : 'text-slate-500 dark:text-slate-400') + '">' + item.icon + '</span>' +
'<span class="text-[10px] leading-none tracking-wide antialiased ' + (active ? 'font-bold' : 'font-medium') + '">' + escapeHTML(item.label) + '</span>' +
'</a>';
}).join('');
syncHomeLinks();
}
function renderDrawerMore() {
var host = document.getElementById('drawer-more');
if (!host) return;
// Live platform rule: everything not flagged showInBottom.
var items = allNavItems().filter(function (i) { return !i.showInBottom; });
if (items.length === 0) {
host.innerHTML = '<p class="px-3 py-2 text-xs text-slate-500 dark:text-gray-400">All items are in your bottom bar. Customize in Profile → Bottom navigation.</p>';
return;
}
host.innerHTML = items.map(function (item) {
var active = VIRTUAL_PATH.indexOf(item.href) === 0;
return '' +
'<a href="' + absUrl(item.href) + '" data-drawer-link class="group flex items-center gap-2.5 rounded-[10px] px-2.5 py-2 text-[13px] font-medium tracking-tight transition-all duration-150 ease-out ' + (active ? 'bg-indigo-50 text-indigo-700 ring-1 ring-indigo-200/60 dark:bg-indigo-500/10 dark:text-indigo-200 dark:ring-indigo-500/20' : 'text-slate-600 hover:bg-slate-100/80 hover:text-slate-900 dark:text-slate-400 dark:hover:bg-slate-800/70 dark:hover:text-slate-100') + '">' +
'<span class="material-symbols-rounded shrink-0 text-[22px] transition-colors duration-150 ' + (active ? 'text-indigo-600 dark:text-indigo-300' : 'text-slate-500 group-hover:text-slate-700 dark:text-slate-500 dark:group-hover:text-slate-300') + '">' + item.icon + '</span>' +
'<span class="truncate">' + escapeHTML(item.label) + '</span>' +
(active ? '<span class="ml-auto h-1.5 w-1.5 shrink-0 rounded-full bg-indigo-600 dark:bg-indigo-400"></span>' : '') +
'</a>';
}).join('');
host.querySelectorAll('[data-drawer-link]').forEach(function (a) {
a.addEventListener('click', closeDrawer);
});
}
function renderAllNav() {
renderRailNav();
renderBottomNav();
renderDrawerMore();
}
/* ---- Rail collapse (same `rail_collapsed` key as the platform) ---- */
function setRailCollapsed(collapsed) {
var rail = document.getElementById('site-rail');
if (!rail) return;
rail.classList.toggle('w-[72px]', collapsed);
rail.classList.toggle('w-[280px]', !collapsed);
var pairs = [
['rail-nav-collapsed', true], ['rail-nav-expanded', false],
['rail-footer-collapsed', true], ['rail-footer-expanded', false]
];
pairs.forEach(function (pair) {
var el = document.getElementById(pair[0]);
if (!el) return;
var showWhenCollapsed = pair[1];
var show = collapsed === showWhenCollapsed;
el.classList.toggle('hidden', !show);
el.classList.toggle('flex', show && showWhenCollapsed);
});
var logoWrap = document.getElementById('rail-logo-wrap');
if (logoWrap) {
logoWrap.classList.toggle('w-0', collapsed);
logoWrap.classList.toggle('opacity-0', collapsed);
logoWrap.classList.toggle('pointer-events-none', collapsed);
logoWrap.classList.toggle('w-[200px]', !collapsed);
logoWrap.classList.toggle('opacity-100', !collapsed);
}
var toggle = document.getElementById('rail-toggle');
if (toggle) toggle.setAttribute('aria-label', collapsed ? 'Expand sidebar' : 'Collapse sidebar');
try {
localStorage.setItem(RAIL_KEY, String(collapsed));
} catch (e) {}
}
function initRail() {
var collapsed = false;
try {
collapsed = localStorage.getItem(RAIL_KEY) === 'true';
} catch (e) {}
setRailCollapsed(collapsed);
var toggle = document.getElementById('rail-toggle');
if (toggle) {
toggle.addEventListener('click', function () {
var rail = document.getElementById('site-rail');
setRailCollapsed(!rail.classList.contains('w-[72px]'));
});
}
document.querySelectorAll('[data-set-theme]').forEach(function (btn) {
btn.addEventListener('click', function () {
var val = btn.getAttribute('data-set-theme');
if (val === 'light' || val === 'dark' || val === 'system') {
currentTheme = val;
applyTheme();
}
});
});
var cycle = document.getElementById('rail-theme-toggle');
if (cycle) cycle.addEventListener('click', cycleTheme);
refreshAppearanceSegmented();
}
/* ---- Drawer (focus trap + Escape + overlay + body lock, like useDialogA11y) ---- */
var drawerLastFocused = null;
var drawerKeyHandler = null;
function drawerFocusables() {
var panel = document.getElementById('drawer-panel');
if (!panel) return [];
return Array.from(panel.querySelectorAll('a[href], button:not([disabled]), [tabindex]:not([tabindex="-1"])'))
.filter(function (el) { return el.offsetParent !== null; });
}
function openDrawer() {
var root = document.getElementById('drawer-root');
var panel = document.getElementById('drawer-panel');
if (!root || !panel) return;
drawerLastFocused = document.activeElement;
root.classList.remove('hidden');
root.classList.add('flex');
document.body.style.overflow = 'hidden';
requestAnimationFrame(function () {
requestAnimationFrame(function () {
panel.classList.remove('-translate-x-full');
});
});
setTimeout(function () {
var closeBtn = document.getElementById('drawer-close');
if (closeBtn) closeBtn.focus();
}, 60);
drawerKeyHandler = function (e) {
if (e.key === 'Escape') {
closeDrawer();
return;
}
if (e.key !== 'Tab') return;
var items = drawerFocusables();
if (items.length === 0) return;
var first = items[0];
var last = items[items.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
};
document.addEventListener('keydown', drawerKeyHandler);
}
function closeDrawer() {
var root = document.getElementById('drawer-root');
var panel = document.getElementById('drawer-panel');
if (!root || !panel || root.classList.contains('hidden')) return;
panel.classList.add('-translate-x-full');
document.body.style.overflow = '';
if (drawerKeyHandler) {
document.removeEventListener('keydown', drawerKeyHandler);
drawerKeyHandler = null;
}
// Match the platform's leave transition before unmounting.
setTimeout(function () {
root.classList.add('hidden');
root.classList.remove('flex');
}, 200);
if (drawerLastFocused && document.contains(drawerLastFocused) && drawerLastFocused instanceof HTMLElement) {
drawerLastFocused.focus();
}
drawerLastFocused = null;
}
function initDrawer() {
var openBtn = document.getElementById('drawer-open');
if (openBtn) openBtn.addEventListener('click', openDrawer);
var closeBtn = document.getElementById('drawer-close');
if (closeBtn) closeBtn.addEventListener('click', closeDrawer);
var overlay = document.getElementById('drawer-overlay');
if (overlay) overlay.addEventListener('click', closeDrawer);
// Note: [data-drawer-link] rows are rendered by renderDrawerMore(),
// which binds their close-on-navigate handler itself.
}
/* ---- RGC is a web page, not an installable app: no manifest,
no beforeinstallprompt handling, no install buttons. ---- */
/* ---- Logout modal ---- */
function openLogoutModal() {
var modal = document.getElementById('logout-modal');
if (!modal) return;
modal.classList.remove('hidden');
modal.classList.add('flex');
document.body.style.overflow = 'hidden';
}
function closeLogoutModal() {
var modal = document.getElementById('logout-modal');
if (!modal) return;
modal.classList.add('hidden');
modal.classList.remove('flex');
document.body.style.overflow = '';
}
function initLogoutModal() {
var c1 = document.getElementById('logout-modal-cancel');
if (c1) c1.addEventListener('click', closeLogoutModal);
var c2 = document.getElementById('logout-modal-cancel-x');
if (c2) c2.addEventListener('click', closeLogoutModal);
var ov = document.getElementById('logout-modal-overlay');
if (ov) ov.addEventListener('click', closeLogoutModal);
document.querySelectorAll('[data-logout-btn]').forEach(function (b) {
b.addEventListener('click', function () {
closeDrawer();
openLogoutModal();
});
});
}
// State
let cachedAuth = null;
try {
cachedAuth = JSON.parse(localStorage.getItem(AUTH_STORAGE_KEY));
} catch (e) {}
function isLoginRequired() {
if (window.APP_CONFIG && typeof window.APP_CONFIG.is_login_required === 'boolean') {
return window.APP_CONFIG.is_login_required;
}
return true;
}
let isLoggedIn = cachedAuth ? Boolean(cachedAuth.authenticated) : null;
let currentUser = cachedAuth ? cachedAuth.user : null;
let inFlightAuthPromise = null;
// Render initial profile state immediately (0ms delay)
renderUserProfileWidget();
initStaticEventListeners();
let rawData = [];
let filteredData = [];
let currentPage = 1;
let itemsPerPage = 25;
let selectedStudent = null;
let selectedSection = 'all';
// Section calculation logic: 190 students per section (A: 1-190, B: 191-380, C: 381-570, D: 571-750)
function getPossibleSection(indexNumber) {
if (!indexNumber || indexNumber < 1) return 'A';
if (indexNumber <= 190) return 'A';
if (indexNumber <= 380) return 'B';
if (indexNumber <= 570) return 'C';
return 'D';
}
function getSectionBadgeClass(section) {
switch (section) {
case 'A':
return 'bg-emerald-50 text-emerald-700 border border-emerald-200/80 dark:bg-emerald-500/10 dark:text-emerald-300 dark:border-emerald-500/20';
case 'B':
return 'bg-blue-50 text-blue-700 border border-blue-200/80 dark:bg-blue-500/10 dark:text-blue-300 dark:border-blue-500/20';
case 'C':
return 'bg-purple-50 text-purple-700 border border-purple-200/80 dark:bg-purple-500/10 dark:text-purple-300 dark:border-purple-500/20';
case 'D':
return 'bg-amber-50 text-amber-700 border border-amber-200/80 dark:bg-amber-500/10 dark:text-amber-300 dark:border-amber-500/20';
default:
return 'bg-slate-100 text-slate-700 border border-slate-200 dark:bg-slate-800 dark:text-slate-300 dark:border-slate-700';
}
}
// Search UI Mode State: 'all' | 'multi_select' | 'sequence_context'
let currentViewMode = 'all';
let lastSearchQuery = '';
let multiMatchList = [];
let focusedTargetRoll = null;
function initStaticEventListeners() {
// Platform shell boot (RGC is not installable: no PWA init by design).
initRail();
initDrawer();
initLogoutModal();
var cachedSpec = loadCachedNavSpec();
if (cachedSpec) currentNavSpec = cachedSpec;
renderAllNav();
refreshNavSpec();
syncHomeLinks();
const toastPill = document.getElementById('toast-pill');
if (toastPill) toastPill.addEventListener('click', hideToast);
var themeToggleBtn = document.getElementById('theme-toggle-btn');
if (themeToggleBtn) {
refreshThemeIcon();
themeToggleBtn.addEventListener('click', cycleTheme);
}
if (authLoginBtn) {
authLoginBtn.href = 'https://hscstack.site/login?redirect=' + encodeURIComponent(window.location.href);
authLoginBtn.addEventListener('click', (e) => {
e.preventDefault();
window.location.href = 'https://hscstack.site/login?redirect=' + encodeURIComponent(window.location.href);
});
}
if (authModalClose) {
authModalClose.addEventListener('click', closeAuthModal);
}
if (authModal) {
authModal.addEventListener('click', (e) => {
if (e.target === authModal) closeAuthModal();
});
}
if (welcomeClose) {
welcomeClose.addEventListener('click', closeWelcomeModal);
}
if (welcomeModal) {
welcomeModal.addEventListener('click', (e) => {
if (e.target === welcomeModal) closeWelcomeModal();
});
}
if (openPrivacyBtn) openPrivacyBtn.addEventListener('click', openPrivacyModal);
if (privacyModalClose) privacyModalClose.addEventListener('click', closePrivacyModal);
if (privacyModalOkBtn) privacyModalOkBtn.addEventListener('click', closePrivacyModal);
if (privacyModal) {
privacyModal.addEventListener('click', (e) => {
if (e.target === privacyModal) closePrivacyModal();
});
}
if (studentModalClose) {
studentModalClose.addEventListener('click', closeStudentModal);
}
if (studentModal) {
studentModal.addEventListener('click', (e) => {
if (e.target === studentModal) closeStudentModal();
});
}
if (modalCopyBtn) {
modalCopyBtn.addEventListener('click', () => {
if (selectedStudent && selectedStudent.Roll) {
copyToClipboard(selectedStudent.Roll);
const origSvg = modalCopyBtn.innerHTML;
modalCopyBtn.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="text-emerald-600 dark:text-emerald-400">
<polyline points="20 6 9 17 4 12"></polyline>
</svg>
`;
setTimeout(() => {
modalCopyBtn.innerHTML = origSvg;
}, 1500);
}
});
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
if (welcomeModal && !welcomeModal.classList.contains('hidden')) closeWelcomeModal();
if (studentModal && !studentModal.classList.contains('hidden')) closeStudentModal();
if (privacyModal && !privacyModal.classList.contains('hidden')) closePrivacyModal();
if (authModal && !authModal.classList.contains('hidden')) closeAuthModal();
const logoutModal = document.getElementById('logout-modal');
if (logoutModal && !logoutModal.classList.contains('hidden')) closeLogoutModal();
}
});
}
// Initialize
init();
async function init() {
try {
showState('loading');
// Check auth and load data
const [, response] = await Promise.all([
checkUserAuth(),
loadStudentsData()
]);
// Sort initially by Roll Number
const sortedData = (response || []).slice().sort((a, b) => {
return (a.Roll || '').localeCompare(b.Roll || '');
});
rawData = sortedData.map((item, idx) => {
const indexNumber = idx + 1;
const section = getPossibleSection(indexNumber);
return {
...item,
indexNumber,
section,
searchIndex: `${item.Roll || ''} ${item.Name || ''} ${item.Previous_School || ''} ${item.total_marks || ''} section ${section} sec ${section}`.toLowerCase()
};
});
totalCount.textContent = rawData.length;
if (statStudents) statStudents.textContent = rawData.length;
renderTopFeederSchools(rawData);
const allOption = pageSizeSelect ? pageSizeSelect.querySelector('option[value="all"]') : null;
if (allOption) {
allOption.textContent = `All (${rawData.length})`;
}
if (rawData.length === 0) {
showState('empty');
return;
}
resetToAllStudents();
// Auto-show Welcome Notice once per new browser tab/session
try {
if (!sessionStorage.getItem('rgc_welcome_notice_tab_seen')) {
setTimeout(() => {
openWelcomeModal();
}, 350);
}
} catch (e) {}
// Event Listeners for Search
if (searchForm) {
searchForm.addEventListener('submit', (e) => {
e.preventDefault();
if (isLoggedIn === false) {
openAuthModal();
return;
}
executeSearch();
});
}
searchInput.addEventListener('click', handleSearchFocusOrClick);
searchInput.addEventListener('focus', handleSearchFocusOrClick);
searchInput.addEventListener('input', () => {
const val = searchInput.value.trim();
if (val.length > 0) {
searchClearBtn.classList.remove('hidden');
searchClearBtn.classList.add('flex');
} else {
searchClearBtn.classList.add('hidden');
searchClearBtn.classList.remove('flex');
}
});
searchClearBtn.addEventListener('click', () => {
searchInput.value = '';
searchClearBtn.classList.add('hidden');
searchClearBtn.classList.remove('flex');
resetToAllStudents();
});
// Guard select auth check
function guardSelectAuth(e, selectEl, defaultVal) {
if (!isLoginRequired()) return false;
if (isLoggedIn === false) {
e.preventDefault();
selectEl.blur();
if (defaultVal) selectEl.value = defaultVal;
openAuthModal();
return true;
}
return false;
}
// Section select auth check & handlers
if (sectionSelect) {
sectionSelect.addEventListener('mousedown', (e) => guardSelectAuth(e, sectionSelect, 'all'));
sectionSelect.addEventListener('click', (e) => guardSelectAuth(e, sectionSelect, 'all'));
sectionSelect.addEventListener('focus', (e) => guardSelectAuth(e, sectionSelect, 'all'));
sectionSelect.addEventListener('change', (e) => {
if (guardSelectAuth(e, sectionSelect, 'all')) return;
selectedSection = sectionSelect.value;
if (searchInput.value.trim()) {
executeSearch();
} else {
resetToAllStudents();
}
});
}
// Sort select auth check & handlers
sortSelect.addEventListener('mousedown', (e) => guardSelectAuth(e, sortSelect, 'roll-asc'));
sortSelect.addEventListener('click', (e) => guardSelectAuth(e, sortSelect, 'roll-asc'));
sortSelect.addEventListener('focus', (e) => guardSelectAuth(e, sortSelect, 'roll-asc'));
sortSelect.addEventListener('change', (e) => {
if (guardSelectAuth(e, sortSelect, 'roll-asc')) return;
if (currentViewMode === 'all') {
applySorting();
renderLeaderboard();
}
});
// Page size select auth check & handlers
pageSizeSelect.addEventListener('mousedown', (e) => guardSelectAuth(e, pageSizeSelect, '25'));
pageSizeSelect.addEventListener('click', (e) => guardSelectAuth(e, pageSizeSelect, '25'));
pageSizeSelect.addEventListener('focus', (e) => guardSelectAuth(e, pageSizeSelect, '25'));
pageSizeSelect.addEventListener('change', (e) => {
if (guardSelectAuth(e, pageSizeSelect, '25')) return;
const val = e.target.value;
itemsPerPage = val === 'all' ? (rawData.length || 1000) : (parseInt(val, 10) || 25);
currentPage = 1;
renderLeaderboard();
});
btnPrev.addEventListener('click', () => {
if (isLoggedIn === false) {
openAuthModal();
return;
}
if (currentPage > 1) {
currentPage--;
renderLeaderboard();
window.scrollTo({ top: 0, behavior: 'smooth' });
}
});
btnNext.addEventListener('click', () => {
if (isLoggedIn === false) {
openAuthModal();
return;
}
const totalPages = Math.ceil(filteredData.length / itemsPerPage);
if (currentPage < totalPages) {
currentPage++;
renderLeaderboard();
window.scrollTo({ top: 0, behavior: 'smooth' });
}
});
} catch (err) {
console.error('Initialization error:', err);
showState('empty');
}
}
async function loadStudentsData() {
if (window.INITIAL_STUDENTS_DATA && Array.isArray(window.INITIAL_STUDENTS_DATA)) {
return window.INITIAL_STUDENTS_DATA;
}
try {
const res = await fetch('students.json');
if (res.ok) {
return await res.json();
}
} catch (e) {
console.warn('Direct fetch failed, falling back:', e);
}
return [];
}
// Auth System
async function checkUserAuth() {
if (inFlightAuthPromise) {
return inFlightAuthPromise;
}
inFlightAuthPromise = (async () => {
let serverErrorOrTimeout = false;
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 2500);
const res = await fetch('https://hscstack.site/api/auth/status', {
method: 'GET',
credentials: 'include',
signal: controller.signal
});
clearTimeout(timeoutId);
if (res.ok) {
const data = await res.json();
if (data.authenticated) {
isLoggedIn = true;
currentUser = data.user || { name: 'User' };
localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify({ authenticated: true, user: currentUser }));
} else {
isLoggedIn = false;
currentUser = null;
}
} else {
serverErrorOrTimeout = true;
}
} catch (e) {
serverErrorOrTimeout = true;
} finally {
inFlightAuthPromise = null;
renderUserProfileWidget();
}
if (serverErrorOrTimeout) {
return true;
}
return Boolean(isLoggedIn);
})();
return inFlightAuthPromise;
}
function authAvatarHtml(sizeClass, textClass) {
const name = (currentUser && currentUser.name) || 'User';
const rawImage = (currentUser && (currentUser.image_url || currentUser.avatar)) || '';
let imageUrl = '';
if (rawImage) {
imageUrl = rawImage.startsWith('http') ? rawImage : `https://hscstack.site${rawImage}`;
}
const initial = (name.trim().charAt(0).toUpperCase() || 'U').replace(/"/g, '');
if (imageUrl) {
return `<img src="${imageUrl}" alt="${escapeHTML(name)}" class="${sizeClass} rounded-full object-cover ring-1 ring-slate-200 dark:ring-slate-700" />`;
}
return `<span class="flex ${sizeClass} items-center justify-center rounded-full bg-gradient-to-br from-indigo-600 to-violet-600 ${textClass} font-bold text-white ring-1 ring-indigo-600/20">${initial}</span>`;
}
function profileUrl() {
if (currentUser && currentUser.username) {
return `https://hscstack.site/u/${encodeURIComponent(currentUser.username)}`;
}
return 'https://hscstack.site/profile';
}
function notifBellHtml(btnClass) {
return `<a href="https://hscstack.site/notifications" aria-label="Notifications" title="Notifications" class="${btnClass}"><span class="material-symbols-rounded text-[22px]">notifications</span></a>`;
}
// Renders every auth-dependent shell slot (rail / drawer / topbar /
// bottom bar) — the same surfaces the platform fills from page.props.
function renderUserProfileWidget() {
const loggedIn = !!(isLoggedIn && currentUser);
const name = loggedIn ? currentUser.name || 'User' : '';
const email = loggedIn ? currentUser.email || '' : '';
// Mobile topbar right: bell when logged in, indigo Login when logged out.
const topbar = document.getElementById('topbar-auth');
if (topbar) {
topbar.innerHTML = loggedIn
? notifBellHtml('flex h-9 w-9 items-center justify-center rounded-full text-slate-600 transition-colors hover:bg-slate-100 hover:text-slate-900 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-slate-100')
: `<a href="https://hscstack.site/login" class="flex h-8 items-center gap-1.5 rounded-lg bg-indigo-600 px-3 text-[13px] font-semibold text-white transition-colors hover:bg-indigo-700 dark:bg-indigo-500 dark:hover:bg-indigo-400"><span class="material-symbols-rounded text-[18px]">login</span>Login</a>`;
}
// Rail expanded footer auth card.
const railAuth = document.getElementById('rail-auth-expanded');
if (railAuth) {
railAuth.innerHTML = loggedIn
? `<div class="flex items-center justify-between gap-3 rounded-xl border bg-white px-3 py-2.5 shadow-sm dark:border-slate-700 dark:bg-slate-800">` +
`<a href="${profileUrl()}" class="flex min-w-0 items-center gap-2.5">${authAvatarHtml('h-8 w-8', 'text-xs')}` +
`<div class="min-w-0 text-left"><p class="truncate text-xs font-semibold text-slate-900 dark:text-slate-100">${escapeHTML(name)}</p>` +
`<p class="truncate text-[11px] text-slate-500 dark:text-slate-400">${escapeHTML(email)}</p></div></a>` +
`<div class="flex shrink-0 items-center gap-1"><button type="button" data-logout-btn title="Log out" aria-label="Log out" class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-rose-500 transition-colors hover:bg-rose-50 hover:text-rose-600 hover:shadow-sm dark:text-rose-400 dark:hover:bg-rose-950/40 dark:hover:text-rose-300"><span class="material-symbols-rounded text-[20px]">logout</span></button></div></div>`
: `<a href="https://hscstack.site/login" aria-label="Login" class="flex h-11 w-full items-center justify-center gap-2.5 rounded-xl border border-transparent bg-indigo-600 px-3 text-[13px] font-bold text-white shadow-sm transition-all duration-150 hover:border-indigo-700 hover:bg-indigo-700 hover:shadow-md dark:border-transparent dark:bg-indigo-500 dark:hover:border-indigo-400 dark:hover:bg-indigo-400"><span class="material-symbols-rounded text-[20px]">login</span><span>Login</span></a>`;
}
// Rail collapsed footer auth.
const railAuthCol = document.getElementById('rail-auth-collapsed');
if (railAuthCol) {
railAuthCol.innerHTML = loggedIn
? `<a href="${profileUrl()}" title="Profile" aria-label="Profile" class="flex items-center justify-center">${authAvatarHtml('h-8 w-8', 'text-xs')}</a>`
: `<a href="https://hscstack.site/login" title="Login" aria-label="Login" class="flex h-10 w-full items-center justify-center rounded-xl border border-transparent bg-indigo-600 text-white shadow-sm transition-all hover:bg-indigo-700 dark:bg-indigo-500 dark:hover:bg-indigo-400"><span class="material-symbols-rounded text-[20px]">login</span></a>`;
}
// Rail notifications rows (deep-link; the live dropdown needs same-origin auth).
const railNotif = document.getElementById('rail-notif-expanded');
if (railNotif) {
railNotif.innerHTML = loggedIn
? `<div class="flex h-11 w-full items-center justify-start gap-2.5 px-3">` +
notifBellHtml('flex items-center justify-center text-slate-600 transition-colors hover:text-slate-900 dark:text-slate-400 dark:hover:text-slate-100') +
`<a href="https://hscstack.site/notifications" class="flex-1 truncate text-left text-[13px] font-semibold text-slate-600 transition-colors hover:text-slate-900 dark:text-slate-400 dark:hover:text-slate-100">Notifications</a></div>`
: '';
}
const railNotifCol = document.getElementById('rail-notif-collapsed');
if (railNotifCol) {
railNotifCol.innerHTML = loggedIn
? notifBellHtml('flex h-10 w-full items-center justify-center rounded-xl text-slate-600 transition-colors hover:bg-slate-100/80 hover:text-slate-900 dark:text-slate-400 dark:hover:bg-slate-800/70 dark:hover:text-slate-100')
: '';
}
// Drawer pinned footer auth (avatar h-9 + "Sign in", like the platform).
const drawerAuth = document.getElementById('drawer-auth');
if (drawerAuth) {
drawerAuth.innerHTML = loggedIn
? `<div class="flex items-center gap-2.5 rounded-xl border bg-white px-3 py-2.5 shadow-sm dark:border-slate-700 dark:bg-slate-800">` +
`<a href="${profileUrl()}" class="flex min-w-0 flex-1 items-center gap-2.5" title="Profile" aria-label="Profile">${authAvatarHtml('h-9 w-9', 'text-xs')}` +
`<span class="min-w-0 text-left"><span class="block truncate text-sm font-semibold text-slate-900 dark:text-slate-100">${escapeHTML(name)}</span>` +