Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
2632 lines (2335 loc) · 109 KB
/
Copy pathapp.js
File metadata and controls
2632 lines (2335 loc) · 109 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
/* global ORGS, openModal, toggleCompare, toggleBookmark, openRandomOrg, clearAllFilters, openCompareModal, fetchModalGH, unselectLanguage, clearAllLanguages */
/* exported openAnalytics, closeAnEvent, fetchAll, fetchModalGH, toggleCompareFromModal, openCompare, closeCompareEv, imgErr, toggleBookmark, toggleChip, resetFilters, closeModalEv, openIssuesPage, closeIssuesPage, fetchAllIssues, showMoreIssues */
// ══════════════════════════════════════════════
// GLOBAL STATE & COMPATIBILITY LAYER
// ══════════════════════════════════════════════
let filteredOrgs = [];
let MENTOR_DATA = {};
let mentorDataState = 'idle';
const compareList = []; // list of org names
const bookmarkedSet = new Set(parseStoredBookmarks());
// Recently Viewed Organizations
const RECENTLY_VIEWED_KEY = 'recentlyViewedOrgs';
const RECENTLY_VIEWED_LIMIT = 8;
let recentlyViewed = (() => {
try {
const parsed = JSON.parse(localStorage.getItem(RECENTLY_VIEWED_KEY) || '[]');
if (!Array.isArray(parsed)) return [];
return parsed.filter(name => typeof name === 'string');
} catch {
return [];
}
})();
const selectedLanguages = new Set();
let matchAllLanguages = false;
let activeChip = null; // quick-filter chip key
let visibleCount = 12;
let focusedIdx = -1; // for keyboard card navigation
// Expose globals for external components (recommender, recommendation-ui, etc.)
globalThis.pills = selectedLanguages;
globalThis.matchAllLanguages = matchAllLanguages;
globalThis.compareList = compareList;
globalThis.bookmarkedSet = bookmarkedSet;
const CATEGORY_META = {
science: { className: 'bg-blue-100 text-blue-700', label: 'Science' },
programming: { className: 'bg-violet-100 text-violet-700', label: 'Programming' },
data: { className: 'bg-cyan-100 text-cyan-700', label: 'Data' },
web: { className: 'bg-green-100 text-green-700', label: 'Web' },
os: { className: 'bg-orange-100 text-orange-700', label: 'OS / Systems' },
security: { className: 'bg-red-100 text-red-700', label: 'Security' },
media: { className: 'bg-pink-100 text-pink-700', label: 'Media' },
infra: { className: 'bg-yellow-100 text-yellow-700', label: 'Infrastructure' },
ai: { className: 'bg-purple-100 text-purple-700', label: 'AI / ML' },
dev: { className: 'bg-teal-100 text-teal-700', label: 'Dev Tools' },
other: { className: 'bg-zinc-100 text-zinc-600', label: 'Other' },
};
const LANGUAGE_ALIASES = {
'python': ['python'],
'javascript': ['javascript', 'js'],
'typescript': ['typescript', 'ts'],
'c/c++': ['c', 'c++', 'cpp'],
'java': ['java'],
'rust': ['rust'],
'go': ['go', 'golang'],
'ruby': ['ruby'],
'haskell': ['haskell'],
'scala': ['scala'],
'ml/ai': ['ml', 'ai', 'machine learning', 'artificial intelligence'],
'robotics': ['robotics', 'robot', 'ros']
};
const LANGUAGE_MAP = {};
(() => {
const toDisplayKey = (k) => {
if (k === 'ml/ai') return 'ML/AI';
if (k === 'c/c++') return 'C/C++';
return k.split(/[\s/]+/).map(p => p.charAt(0).toUpperCase() + p.slice(1)).join(' ');
};
Object.keys(LANGUAGE_ALIASES).forEach(k => {
const display = toDisplayKey(k);
LANGUAGE_MAP[display] = LANGUAGE_ALIASES[k];
LANGUAGE_MAP[k] = LANGUAGE_ALIASES[k];
});
})();
globalThis.LANGUAGE_MAP = LANGUAGE_MAP;
const UMBRELLA_ORGS = new Set([
'Apache Software Foundation', 'CNCF', 'Eclipse Foundation', 'FOSSASIA', 'GNOME Foundation',
'GNU Project', 'Jenkins', 'KDE Community', 'NumFOCUS', 'OpenMRS', 'openSUSE Project',
'OWASP Foundation', 'The Linux Foundation', 'Wikimedia Foundation', 'AOSSIE', 'CERN-HSF',
'CCExtractor Development', 'Blender Foundation', 'Open Robotics', 'JBoss Community',
'The Honeynet Project', 'MetaBrainz Foundation Inc', 'OSGeo (Open Source Geospatial Foundation)',
'SW360', 'DBpedia', 'LibreOffice', 'Oppia Foundation', 'Sugar Labs', 'Internet Archive',
'VideoLAN', 'JdeRobot', 'Kubeflow', 'INCF', 'OpenAstronomy', 'Machine Learning for Science (ML4SCI)',
'SageMath', 'National Resource for Network Biology (NRNB)', 'FOSSology', 'JabRef e.V.',
'LabLua', 'Liquid Galaxy project', 'Free and Open Source Silicon Foundation',
]);
const CHANNEL_ICONS = {
Slack: '💬', Zulip: '💬', Discord: '🎮', Matrix: '🔗', IRC: '🖥️', 'Mailing list': '📧'
};
const CONTACT_TIPS = {
Slack: 'Join and say hi in the GSoC channel before DMing mentors.',
Discord: 'Introduce yourself in the public channel before asking project-specific questions.',
Zulip: 'Post a new topic in the GSoC stream with your background and interest.',
Matrix: "Say hello in the public room and mention the project area you're exploring.",
IRC: 'Stay in the channel for a while; replies are often asynchronous.',
'Mailing list': "Send a short intro email with your background and the idea you're interested in."
};
// ══════════════════════════════════════════════
// THEME & FOUC PROTECTION
// ══════════════════════════════════════════════
(function initTheme() {
try {
const saved = localStorage.getItem('theme') || 'light';
document.documentElement.classList.toggle('dark', saved === 'dark');
updateThemeIcon();
} catch (e) {
console.warn('Theme init failed:', e);
}
})();
globalThis.toggleTheme = function () {
const isDark = document.documentElement.classList.toggle('dark');
localStorage.setItem('theme', isDark ? 'dark' : 'light');
updateThemeIcon();
};
function updateThemeIcon() {
const btn = document.getElementById('themeToggleBtn');
const icon = btn ? btn.querySelector('.material-symbols-outlined') : null;
if (icon) {
const isDark = typeof document.documentElement.classList.contains === 'function'
? document.documentElement.classList.contains('dark')
: false;
icon.textContent = isDark ? 'light_mode' : 'dark_mode';
btn.setAttribute('aria-pressed', isDark ? 'true' : 'false');
btn.setAttribute('aria-label', isDark ? 'Switch to light theme' : 'Switch to dark theme');
btn.setAttribute('title', isDark ? 'Switch to light theme' : 'Switch to dark theme');
}
}
// ══════════════════════════════════════════════
// DYNAMIC TIMELINE & COUNTDOWN
// ══════════════════════════════════════════════
const GSOC_SELECTION_DATE = new Date('2026-05-08T18:00:00Z');
const MILESTONES = [
{ date: new Date('2026-02-19T00:00:00Z'), label: 'Accepted Orgs Announced', note: null },
{ date: new Date('2026-03-16T00:00:00Z'), label: 'Contributor Proposals Open', note: null },
{ date: new Date('2026-03-31T23:30:00+05:30'), label: 'Proposal Submission Deadline', note: 'Submit your project proposals by 11:30 PM!' },
{ date: GSOC_SELECTION_DATE, label: 'Accepted Projects Announced', note: null },
{ date: new Date('2026-05-25T00:00:00Z'), label: 'Coding Officially Begins', note: 'Start working on your GSoC project!' },
{ date: new Date('2026-07-06T18:00:00Z'), label: 'Midterm Evaluations Begin', note: 'Mentors and contributors submit midterm evaluations.' },
{ date: new Date('2026-07-10T18:00:00Z'), label: 'Midterm Evaluation Deadline', note: null },
{ date: new Date('2026-08-17T00:00:00Z'), label: 'Final Submissions Begin', note: 'Submit your final work product and evaluation.' },
{ date: new Date('2026-08-24T18:00:00Z'), label: 'Final Submission Deadline (Standard)', note: 'Standard 12-week projects: submit final work product and evaluation.' },
{ date: new Date('2026-08-31T18:00:00Z'), label: 'Mentor Final Evaluations Due (Standard)', note: null },
{ date: new Date('2026-11-02T18:00:00Z'), label: 'Extended Timeline Final Deadline', note: 'Last date for all contributors on extended timelines to submit final work.' },
{ date: new Date('2026-11-09T18:00:00Z'), label: 'Extended Mentor Evaluations Due', note: 'Final date for mentors to submit evaluations for extended projects.' },
].filter(m => !isNaN(m.date.getTime()));
function renderTimeline() {
const container = document.getElementById('timeline-milestones');
if (!container || MILESTONES.length === 0) return;
try {
const now = new Date();
if (isNaN(now.getTime())) return;
let activeIdx = MILESTONES.findIndex(m => m.date > now);
if (activeIdx === -1) activeIdx = MILESTONES.length - 1;
const allPast = MILESTONES[MILESTONES.length - 1].date <= now;
container.innerHTML = MILESTONES.map((m, i) => {
const isActive = i === activeIdx;
const isLast = i === MILESTONES.length - 1;
const connector = !isLast ? `<div class="w-0.5 h-10 bg-zinc-200 dark:bg-zinc-700"></div>` : '';
let dateStr;
try {
dateStr = m.date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }).toUpperCase();
} catch (err) {
console.warn('[Timeline] Date formatting failed for:', m.date, err);
dateStr = m.date.toISOString().slice(0, 10);
}
if (isActive && !allPast) {
return `<div class="flex gap-3 sm:gap-4">
<div class="flex flex-col items-center"><div class="w-3 h-3 rounded-full bg-primary ring-4 ring-orange-100 dark:ring-orange-950/40 pulse-dot"></div>${connector}</div>
<div><p class="text-[10px] font-bold text-primary">${escapeHtml(dateStr)}</p>
<p class="text-sm sm:text-base font-extrabold text-zinc-900 dark:text-zinc-100 leading-tight">${escapeHtml(m.label)}</p>
${m.note ? `<p class="text-xs text-zinc-500 dark:text-zinc-400 mt-1">${escapeHtml(m.note)}</p>` : ''}</div>
</div>`;
} else if (isActive && allPast) {
return `<div class="flex gap-3 sm:gap-4">
<div class="flex flex-col items-center"><div class="w-3 h-3 rounded-full bg-green-500 ring-4 ring-green-100 dark:ring-green-950/40"></div>${connector}</div>
<div><p class="text-[10px] font-bold text-green-600">${escapeHtml(dateStr)}</p>
<p class="text-sm sm:text-base font-extrabold text-zinc-900 dark:text-zinc-100 leading-tight">${escapeHtml(m.label)}</p>
<p class="text-xs text-green-600 dark:text-green-400 mt-1">✓ Completed</p></div>
</div>`;
} else {
return `<div class="flex gap-3 sm:gap-4 opacity-40">
<div class="flex flex-col items-center"><div class="w-2 h-2 rounded-full bg-zinc-300 dark:bg-zinc-600"></div>${connector}</div>
<div><p class="text-[10px] font-bold text-zinc-400">${escapeHtml(dateStr)}</p>
<p class="text-sm font-bold text-zinc-500 dark:text-zinc-400">${escapeHtml(m.label)}</p></div>
</div>`;
}
}).join('');
} catch (err) {
console.warn('[Timeline] renderTimeline failed:', err);
}
}
function updateCountdown() {
const countdownEl = document.getElementById('countdown');
const labelEl = document.getElementById('countdown-label');
if (!countdownEl || !labelEl || MILESTONES.length === 0) return;
try {
const now = new Date();
if (isNaN(now.getTime())) return;
const next = MILESTONES.find(m => m.date > now);
if (!next) {
labelEl.textContent = 'GSoC 2026 selection complete';
countdownEl.textContent = '🎉 All done!';
countdownEl.classList.remove('text-primary');
countdownEl.classList.add('text-green-600');
return;
}
labelEl.textContent = `Until: ${next.label}`;
countdownEl.classList.remove('text-green-600');
countdownEl.classList.add('text-primary');
const diff = next.date - now;
if (diff <= 0) { renderTimeline(); updateCountdown(); return; }
const d = Math.floor(diff / 864e5), h = Math.floor((diff % 864e5) / 36e5), m = Math.floor((diff % 36e5) / 6e4);
countdownEl.textContent = `${d}d ${h}h ${m}m`;
} catch (err) {
console.warn('[Timeline] updateCountdown failed:', err);
}
}
// ══════════════════════════════════════════════
// ANALYTICS ENGINE
// ══════════════════════════════════════════════
const AN = {
g(k, d) { try { return JSON.parse(localStorage.getItem('gaf_' + k)) ?? d; } catch { return d; } },
s(k, v) {
try {
localStorage.setItem('gaf_' + k, JSON.stringify(v));
} catch (err) {
console.warn('Analytics storage write failed for key:', k, err);
}
},
inc(k) { this.s(k, (this.g(k, 0) + 1)); },
push(k, v, max = 20) { const a = this.g(k, []); a.unshift(v); this.s(k, a.slice(0, max)); },
today() { return new Date().toISOString().slice(0, 10); },
trackVisit() {
this.inc('total');
const td = this.today(), daily = this.g('daily', {});
daily[td] = (daily[td] || 0) + 1; this.s('daily', daily);
if (!sessionStorage.getItem('gaf_s')) sessionStorage.setItem('gaf_s', Date.now());
},
trackSearch(t) { if (t.length > 1) { this.inc('searches'); this.push('sterms', t.toLowerCase().trim()); } },
trackCat(c) { if (c) { this.inc('filters'); const cf = this.g('cats', {}); cf[c] = (cf[c] || 0) + 1; this.s('cats', cf); } },
trackOrg(n) { this.inc('views'); const oc = this.g('orgs', {}); oc[n] = (oc[n] || 0) + 1; this.s('orgs', oc); },
todayVisits() { return this.g('daily', {})[this.today()] || 0; },
sessionTime() {
const s = sessionStorage.getItem('gaf_s'); if (!s) return '—';
const sec = Math.floor((Date.now() - parseInt(s)) / 1000);
return sec < 60 ? sec + 's' : Math.floor(sec / 60) + 'm' + (sec % 60) + 's';
},
topCats() { return Object.entries(this.g('cats', {})).sort((a, b) => b[1] - a[1]).slice(0, 6); },
topOrgs() { return Object.entries(this.g('orgs', {})).sort((a, b) => b[1] - a[1]).slice(0, 5); },
topTerms() { const f = {}; this.g('sterms', []).forEach(t => { f[t] = (f[t] || 0) + 1; }); return Object.entries(f).sort((a, b) => b[1] - a[1]).slice(0, 12); }
};
AN.trackVisit();
function renderTrending() {
const top = AN.topOrgs();
const sec = document.getElementById('trendingSection');
const scroll = document.getElementById('trendingScroll');
if (!top.length || !sec || !scroll) { if (sec) sec.style.display = 'none'; return; }
sec.style.display = 'block';
scroll.innerHTML = top.map(([name, views], i) => {
const o = ORGS.find(x => x.name === name);
if (!o) return '';
return safeHTML`<div class="trend-card bg-white dark:bg-zinc-800 border border-zinc-100 dark:border-zinc-700" data-org-name="${o.name}">
<div class="trend-rank">${String(i + 1)}</div>
<div class="trend-info">
<div class="trend-name">${name}</div>
<div class="trend-views">${String(views)} view${views !== 1 ? 's' : ''} · ${getCategoryMeta(o.cat).label}</div>
</div>
</div>`;
}).join('');
}
globalThis.openAnalytics = function () {
const aTot = document.getElementById('aTot');
if (!aTot) return;
aTot.textContent = AN.g('total', 0).toLocaleString();
document.getElementById('aToday').textContent = AN.todayVisits();
document.getElementById('aSearches').textContent = AN.g('searches', 0);
document.getElementById('aViews').textContent = AN.g('views', 0);
document.getElementById('aFilters').textContent = AN.g('filters', 0);
document.getElementById('aTime').textContent = AN.sessionTime();
const tc = AN.topCats(), mx = tc[0]?.[1] || 1;
document.getElementById('catChart').innerHTML = tc.length
? tc.map(([c, n]) => `<div class="bar-row"><span class="bar-lbl">${escapeHtml(getCategoryMeta(c).label)}</span><div class="bar-track"><div class="bar-fill" style="width:${Math.round(n / mx * 100)}%"></div></div><span class="bar-val">${escapeHtml(String(n))}</span></div>`).join('')
: '<span style="color:var(--muted);font-size:12px">Use category filters to track data</span>';
const to = AN.topOrgs(), mo = to[0]?.[1] || 1;
document.getElementById('orgChart').innerHTML = to.length
? to.map(([o, n]) => `<div class="bar-row"><span class="bar-lbl" style="font-size:10px">${escapeHtml(o.length > 16 ? o.slice(0, 16) + '…' : o)}</span><div class="bar-track"><div class="bar-fill" style="width:${Math.round(n / mo * 100)}%"></div></div><span class="bar-val">${escapeHtml(String(n))}</span></div>`).join('')
: '<span style="color:var(--muted);font-size:12px">Click org cards to track views</span>';
const tt = AN.topTerms();
document.getElementById('srchTerms').innerHTML = tt.length
? tt.map(([t, c], i) => `<span class="sch ${i < 3 ? 'hot' : ''}">${escapeHtml(t)} (${escapeHtml(String(c))})</span>`).join('')
: '<span style="color:var(--muted);font-size:12px">No searches yet</span>';
openModalElement('anBg');
};
globalThis.closeAnEvent = function (e) { if (e.target === document.getElementById('anBg')) closeModalElement('anBg'); };
// ══════════════════════════════════════════════
// URL VALIDATION & SANITIZATION HELPERS
// ══════════════════════════════════════════════
function escapeHtml(value) {
return String(value)
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}
// Centralized DOM-Safe Dynamic Rendering
class SafeHTMLString extends String {
constructor(value) {
super(value);
}
}
SafeHTMLString.prototype.__isSafeHTML = true;
function safeHTML(strings, ...values) {
let result = '';
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < values.length) {
const val = values[i];
if (val && val.__isSafeHTML) {
result += val.toString();
} else if (Array.isArray(val)) {
result += val.map(v => (v && v.__isSafeHTML) ? v.toString() : escapeHtml(v)).join('');
} else {
result += escapeHtml(val !== undefined && val !== null ? String(val) : '');
}
}
}
return new SafeHTMLString(result);
}
function rawHTML(value) {
return new SafeHTMLString(value || '');
}
globalThis.safeHTML = safeHTML;
globalThis.rawHTML = rawHTML;
function sanitizeHrefUrl(url) {
if (!url || !String(url).trim()) return null;
try {
const u = new URL(String(url).trim());
if (u.protocol === 'http:' || u.protocol === 'https:') return u.toString();
} catch (err) {
console.debug('Invalid URL or disallowed protocol in sanitizeHrefUrl:', url, err);
}
return null;
}
// ══════════════════════════════════════════════
// URL VALIDATION & SANITIZATION
// ══════════════════════════════════════════════
/**
* Generic URL validator — ensures only http/https protocols are allowed.
* Does NOT auto-prepend a protocol. The caller must pass a fully-formed URL.
*
* @param {string} url - A fully-formed URL string to validate
* @returns {string|null} - The trimmed URL if valid, null otherwise
*/
function validateUrl(url) {
if (!url || !url.trim()) return null;
try {
const trimmed = url.trim();
const urlObj = new URL(trimmed);
if (urlObj.protocol === 'http:' || urlObj.protocol === 'https:') {
return trimmed;
}
console.warn('Rejected non-HTTP(S) URL:', url);
return null;
} catch (e) {
console.warn('Invalid URL format:', url, e);
return null;
}
}
/**
* Validates and sanitizes project ideas URLs for safe display.
* Automatically prepends https:// if no protocol is specified.
* Delegates to validateUrl() for the actual protocol check.
*
* @param {string} ideasUrl - The raw URL string from organization data
* @returns {string|null} - Sanitized URL if valid, null otherwise
*/
function validateIdeasUrl(ideasUrl) {
if (!ideasUrl || !ideasUrl.trim()) return null;
let url = ideasUrl.trim();
if (!url.includes('://')) {
url = 'https://' + url;
}
return validateUrl(url);
}
function getCategoryMeta(category) {
return CATEGORY_META[category] || CATEGORY_META.other;
}
// ══════════════════════════════════════════════
// GITHUB API CLIENT
// ══════════════════════════════════════════════
const API = '/api/github';
const ghCache = (() => {
try {
return JSON.parse(localStorage.getItem('gaf_ghc') || '{}');
} catch {
return {};
}
})();
function saveCache(key, value) {
try {
localStorage.setItem('gaf_ghc', JSON.stringify(ghCache));
} catch (e) {
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
console.warn('LocalStorage quota exceeded, clearing GitHub cache...');
for (const k in ghCache) delete ghCache[k];
if (key && value !== undefined) ghCache[key] = value;
try {
localStorage.setItem('gaf_ghc', JSON.stringify(ghCache));
} catch (err) {
console.error('Failed to save even after clearing cache', err);
}
}
}
}
function cleanCache() {
const now = Date.now();
const ONE_DAY = 24 * 60 * 60 * 1000;
let changed = false;
for (const key in ghCache) {
const entry = ghCache[key];
if (!entry || typeof entry.ts !== 'number' || Number.isNaN(entry.ts) || now - entry.ts > ONE_DAY) {
delete ghCache[key];
changed = true;
}
}
if (changed) saveCache();
}
cleanCache();
async function checkAPI() {
try {
const r = await fetch(`${API}?repo=django/django`);
const banner = document.getElementById('apiBanner');
if (!banner) return;
if (r.ok) {
banner.className = 'api-banner api-ok';
document.getElementById('apiStrong').textContent = '✓ GitHub API Connected';
document.getElementById('apiText').textContent = 'Live stats (stars, forks, good first issues) available for all visitors.';
const fetchBtn = document.getElementById('fetchBtn');
if (fetchBtn) fetchBtn.style.display = 'flex';
} else {
banner.className = 'api-banner api-warn';
document.getElementById('apiStrong').textContent = '⚠ API Error';
document.getElementById('apiText').textContent = 'Add GITHUB_TOKEN in Vercel dashboard and redeploy.';
}
} catch {
const banner = document.getElementById('apiBanner');
if (banner) {
document.getElementById('apiStrong').textContent = '○ Running Locally';
document.getElementById('apiText').textContent = 'Deploy to Vercel for live GitHub stats.';
}
}
}
async function fetchGH(repo) {
if (!repo) return null;
if (ghCache[repo] && Date.now() - ghCache[repo].ts < 3600000) return ghCache[repo];
try {
const r = await fetch(`${API}?repo=${encodeURIComponent(repo)}`);
if (!r.ok) return null;
const d = await r.json();
if (d.error) return null;
d.ts = Date.now();
ghCache[repo] = d;
saveCache(repo, d);
return d;
} catch { return null; }
}
async function fetchGFI(repo) {
if (!repo) return null;
const cacheKey = repo + '__gfi';
const hit = ghCache[cacheKey];
if (hit && Date.now() - hit.ts < 3600000 && hit.count !== null && hit.count !== undefined) return hit.count;
try {
const r = await fetch(`${API}?repo=${encodeURIComponent(repo)}&gfi=1`);
if (!r.ok) return null;
const d = await r.json();
if (d.gfi === null || d.gfi === undefined) return null;
ghCache[cacheKey] = { count: d.gfi, ts: Date.now() };
saveCache(cacheKey, ghCache[cacheKey]);
return d.gfi;
} catch { return null; }
}
// ══════════════════════════════════════════════
// MODAL & KEYBOARD CONTROLLER (ACCESSIBILITY HARDENED)
// ══════════════════════════════════════════════
let activeTriggerElement = null;
function openModalElement(modalId, triggerElement = null) {
const modal = document.getElementById(modalId);
if (!modal) return;
activeTriggerElement = triggerElement || document.activeElement;
if (modalId === 'mobileMenu') {
modal.classList.remove('hidden');
const panel = document.getElementById('menuPanel');
if (panel) setTimeout(() => { panel.style.transform = 'translateX(0)'; }, 10);
const menuBtn = document.getElementById('menuBtn');
if (menuBtn) {
menuBtn.setAttribute('aria-expanded', 'true');
menuBtn.setAttribute('aria-label', 'Close menu');
}
} else {
modal.classList.add('open');
}
modal.setAttribute('aria-hidden', 'false');
document.body.style.overflow = 'hidden';
document.documentElement.style.overflow = 'hidden';
// Set focus to close button
const closeBtn = modal.querySelector('.close-btn, [onclick*="close"]');
if (closeBtn) closeBtn.focus();
modal.addEventListener('keydown', trapFocus);
}
function closeModalElement(modalId) {
const modal = document.getElementById(modalId);
if (!modal) return;
if (modalId === 'mobileMenu') {
const panel = document.getElementById('menuPanel');
if (panel) panel.style.transform = 'translateX(-100%)';
const menuBtn = document.getElementById('menuBtn');
if (menuBtn) {
menuBtn.setAttribute('aria-expanded', 'false');
menuBtn.setAttribute('aria-label', 'Open menu');
}
setTimeout(() => { modal.classList.add('hidden'); }, 300);
} else {
modal.classList.remove('open');
}
modal.setAttribute('aria-hidden', 'true');
document.body.style.overflow = '';
document.documentElement.style.overflow = '';
modal.removeEventListener('keydown', trapFocus);
if (activeTriggerElement) {
activeTriggerElement.focus();
activeTriggerElement = null;
}
}
function trapFocus(e) {
if (e.key !== 'Tab') return;
const modal = e.currentTarget;
const focusables = modal.querySelectorAll('button, [href], input, select, textarea, [tabindex="0"]');
if (!focusables.length) return;
const first = focusables[0];
const last = focusables[focusables.length - 1];
if (e.shiftKey && document.activeElement === first) {
last.focus();
e.preventDefault();
} else if (!e.shiftKey && document.activeElement === last) {
first.focus();
e.preventDefault();
}
}
function toggleMenu() {
const menu = document.getElementById('mobileMenu');
if (menu) {
if (menu.classList.contains('hidden')) {
openModalElement('mobileMenu');
} else {
closeModalElement('mobileMenu');
}
}
}
globalThis.toggleMenu = toggleMenu;
function setActiveMenu(clickedLink) {
const allLinks = document.querySelectorAll('.mobile-menu-link');
allLinks.forEach(link => {
link.classList.remove('text-orange-600', 'bg-orange-50', 'font-bold');
link.classList.add('text-zinc-700', 'hover:bg-zinc-100', 'font-medium');
});
clickedLink.classList.remove('text-zinc-700', 'hover:bg-zinc-100', 'font-medium');
clickedLink.classList.add('text-orange-600', 'bg-orange-50', 'font-bold');
setTimeout(() => {
closeModalElement('mobileMenu');
}, 300);
}
globalThis.setActiveMenu = setActiveMenu;
// Keyboard grid card selection navigation
const GRID_COLS = () => {
const g = document.getElementById('orgGrid');
if (!g || !g.children.length) return 3;
const firstRect = g.children[0].getBoundingClientRect();
let cols = 1;
for (let i = 1; i < g.children.length; i++) {
if (Math.abs(g.children[i].getBoundingClientRect().top - firstRect.top) < 5) cols++;
else break;
}
return cols;
};
function scrollToFocused() {
setTimeout(() => {
const g = document.getElementById('orgGrid');
const card = g?.querySelector(`[data-filtered-idx="${focusedIdx}"]`);
if (card) card.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}, 30);
}
function updateCardFocus() {
const cards = document.querySelectorAll('#orgGrid article');
cards.forEach((card, idx) => {
const isFocused = idx === focusedIdx;
card.classList.toggle('ring-2', isFocused);
card.classList.toggle('ring-primary', isFocused);
});
}
// Global keydown helper functions to manage Cognitive Complexity
function handleEscapeKey(e) {
const activeModal = document.querySelector('.modal-bg.open, #mobileMenu:not(.hidden), .modal-bg.compare-bg.open');
if (activeModal) {
e.preventDefault();
closeModalElement(activeModal.id);
return true;
}
return false;
}
function handleNavigationRight(e, n) {
e.preventDefault();
focusedIdx = Math.min(focusedIdx + 1, n - 1);
if (focusedIdx < 0) focusedIdx = 0;
if (focusedIdx >= visibleCount) {
visibleCount = Math.min(visibleCount + 12, n);
renderOrgs(false);
}
scrollToFocused();
updateCardFocus();
}
function handleNavigationLeft(e) {
e.preventDefault();
focusedIdx = Math.max(focusedIdx - 1, 0);
scrollToFocused();
updateCardFocus();
}
function handleNavigationDown(e, n) {
e.preventDefault();
const cols = GRID_COLS();
focusedIdx = Math.min(focusedIdx + cols, n - 1);
if (focusedIdx < 0) focusedIdx = 0;
if (focusedIdx >= visibleCount) {
visibleCount = Math.min(visibleCount + 12, n);
renderOrgs(false);
}
scrollToFocused();
updateCardFocus();
}
function handleNavigationUp(e) {
e.preventDefault();
const cols = GRID_COLS();
focusedIdx = Math.max(focusedIdx - cols, 0);
scrollToFocused();
updateCardFocus();
}
function handleGlobalKeydown(e) {
if (e.key === 'Escape' && handleEscapeKey(e)) return;
if (['INPUT', 'SELECT', 'TEXTAREA'].includes(document.activeElement?.tagName)) return;
const n = filteredOrgs.length;
if (e.key === '?') {
e.preventDefault();
openModalElement('helpModal');
return;
}
if (e.key === '/') {
e.preventDefault();
document.getElementById('searchInput')?.focus();
return;
}
if (n <= 0) return;
switch (e.key) {
case 'ArrowRight':
handleNavigationRight(e, n);
break;
case 'ArrowLeft':
handleNavigationLeft(e);
break;
case 'ArrowDown':
handleNavigationDown(e, n);
break;
case 'ArrowUp':
handleNavigationUp(e);
break;
case 'Enter':
if (focusedIdx >= 0 && focusedIdx < n) {
e.preventDefault();
openModal(filteredOrgs[focusedIdx].name);
}
break;
case 'c':
case 'C':
if (focusedIdx >= 0 && focusedIdx < n) {
e.preventDefault();
toggleCompare(null, filteredOrgs[focusedIdx].name);
}
break;
}
}
// Global keydown short-router
document.addEventListener('keydown', handleGlobalKeydown);
// ══════════════════════════════════════════════
// BOOKMARK SYSTEM (WATCHLIST)
// ══════════════════════════════════════════════
function parseStoredBookmarks() {
try {
const parsed = JSON.parse(localStorage.getItem('bookmarks') || '[]');
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function syncBookmark(name, shouldAdd) {
if (!name) return;
if (shouldAdd) bookmarkedSet.add(name);
else bookmarkedSet.delete(name);
localStorage.setItem('bookmarks', JSON.stringify([...bookmarkedSet]));
refreshOrgGridAfterBookmarkChange();
renderWatchlist();
updateAIInsights();
}
globalThis.toggleBookmark = function (e, name) {
if (e) e.stopPropagation();
if (!name) return;
syncBookmark(name, !bookmarkedSet.has(name));
};
function refreshVisibleBookmarkButtons() {
document.querySelectorAll('#orgGrid .bookmark-btn[data-bookmark-org]').forEach(btn => {
const name = btn.dataset.bookmarkOrg;
const isBookmarked = bookmarkedSet.has(name);
btn.classList.toggle('active', isBookmarked);
btn.classList.toggle('text-zinc-300', !isBookmarked);
btn.title = isBookmarked ? 'Remove bookmark' : 'Add bookmark';
btn.setAttribute('aria-label', isBookmarked ? `Remove bookmark from ${name}` : `Add bookmark to ${name}`);
const icon = btn.querySelector('.material-symbols-outlined');
if (icon) icon.classList.toggle('icon-fill', isBookmarked);
});
}
function refreshOrgGridAfterBookmarkChange() {
if (activeChip === 'bookmarked') {
applyFiltersPreservingVisibleCount();
return;
}
refreshVisibleBookmarkButtons();
}
function applyFiltersPreservingVisibleCount() {
const savedCount = visibleCount;
applyFilters();
while (visibleCount < savedCount && visibleCount < filteredOrgs.length) {
visibleCount += 12;
renderOrgs(false);
}
}
function clearAllBookmarks() {
if (!bookmarkedSet.size) return;
if (!confirm(`Remove all ${bookmarkedSet.size} bookmarked organization(s)? This cannot be undone.`)) return;
bookmarkedSet.clear();
localStorage.setItem('bookmarks', JSON.stringify([]));
applyFilters();
renderWatchlist();
updateAIInsights();
}
document.getElementById('clearAllBookmarksBtn')?.addEventListener('click', clearAllBookmarks);
function renderWatchlist() {
const container = document.getElementById('watchlistContainer');
const clearBtn = document.getElementById('clearAllBookmarksBtn');
if (!container) return;
container.innerHTML = '';
const bookmarks = [...bookmarkedSet]
.map(name => ORGS.find(o => o.name === name))
.filter(Boolean);
if (clearBtn) clearBtn.classList.toggle('hidden', bookmarks.length === 0);
if (bookmarks.length === 0) {
container.innerHTML = `
<div class="py-16 text-center border-2 border-dashed border-zinc-200 dark:border-zinc-700 rounded-2xl">
<span class="material-symbols-outlined text-4xl text-zinc-300 dark:text-zinc-600 mb-4 block">bookmark_border</span>
<p class="font-bold text-zinc-500 mb-1">Your Watchlist is Empty</p>
<p class="text-sm text-zinc-400">Click the ★ on any organization card to start tracking it here.</p>
</div>`;
return;
}
bookmarks.forEach(org => {
const githubOwner = githubOwnerFromValue(org.github);
const logoUrl = githubOwner ? `https://github.com/${githubOwner}.png?size=80` : '';
const category = getCategoryMeta(org.cat);
const topTags = (org.tags || []).slice(0, 4)
.map(t => safeHTML`<span class="px-2 py-0.5 bg-surface-container-low dark:bg-zinc-800 text-[10px] font-mono rounded text-zinc-600 dark:text-zinc-400">${t}</span>`);
const item = document.createElement('div');
item.className = 'bg-white dark:bg-zinc-900 rounded-2xl p-5 border border-zinc-100 dark:border-zinc-800 flex gap-4 items-start hover:shadow-lg hover:border-primary/20 transition-all animate-fade-up';
item.dataset.watchlistOrg = org.name;
const logoHtml = logoUrl
? safeHTML`<img src="${logoUrl}" data-org-name="${org.name}" alt="${org.name} logo" class="w-full h-full object-contain">`
: safeHTML`<span class="material-symbols-outlined text-primary text-xl">corporate_fare</span>`;
item.innerHTML = safeHTML`
<div class="w-12 h-12 rounded-xl bg-surface-container-low dark:bg-zinc-800 flex items-center justify-center flex-shrink-0 overflow-hidden border border-zinc-100 dark:border-zinc-700">
${logoHtml}
</div>
<div class="flex-1 min-w-0">
<div class="flex items-start justify-between gap-2 mb-1.5 flex-wrap">
<h4 class="font-bold text-zinc-900 dark:text-zinc-100 leading-tight">${org.name}</h4>
<div class="flex items-center gap-2 flex-shrink-0">
<span class="text-[10px] font-label font-bold uppercase tracking-wider px-2 py-0.5 rounded-full ${category.className}">${category.label}</span>
<span class="text-[10px] font-label font-bold uppercase tracking-wider text-white bg-primary px-2 py-0.5 rounded-full">★ Saved</span>
</div>
</div>
<p class="text-sm text-zinc-500 dark:text-zinc-400 mb-3 line-clamp-1">${org.desc || ''}</p>
<div class="flex flex-wrap gap-1.5 mb-3">${topTags}</div>
<div class="flex items-center justify-between pt-3 border-t border-zinc-100 dark:border-zinc-800">
<div class="flex items-center gap-3 text-xs text-zinc-400">
<span class="flex items-center gap-1">
<span class="material-symbols-outlined text-xs">calendar_today</span>
${String(org.years)}y in GSoC
</span>
<span class="flex items-center gap-1">
<span class="material-symbols-outlined text-xs">bar_chart</span>
${org.competition || '—'}
</span>
</div>
<button data-bookmark-org="${org.name}"
class="bookmark-remove-btn text-[10px] font-bold uppercase tracking-widest text-red-400 hover:text-red-600 flex items-center gap-1 transition-colors">
<span class="material-symbols-outlined text-xs">bookmark_remove</span>
Remove
</button>
</div>
</div>`;
container.appendChild(item);
attachOrgCardListeners(item);
});
}
// ══════════════════════════════════════════════
// COMPARE SYSTEM
// ══════════════════════════════════════════════
globalThis.toggleCompare = function (e, name) {
if (e) e.stopPropagation();
if (!name) return;
const idx = compareList.indexOf(name);
if (idx > -1) {
compareList.splice(idx, 1);
} else {
if (compareList.length >= 3) {
alert("You can only compare up to 3 organizations at a time.");
return;
}
compareList.push(name);
}
renderOrgs(true);
renderCompare();
};
function renderCompare() {
const container = document.querySelector('#compare .grid');
if (!container) return;
if (typeof document.createElement !== 'function') return;
container.innerHTML = '';
compareList.forEach(name => {
const org = ORGS.find(o => o.name === name);
if (!org) return;
const githubOwner = githubOwnerFromValue(org.github);
const logoUrl = githubOwner ? `https://github.com/${githubOwner}.png?size=80` : '';
const item = document.createElement('div');
item.className = 'bg-white dark:bg-zinc-900 rounded-xl p-4 border border-zinc-100 dark:border-zinc-800';
item.innerHTML = safeHTML`
<div class="w-10 h-10 rounded-lg bg-orange-100 dark:bg-orange-950/40 flex items-center justify-center mx-auto mb-3 overflow-hidden">
<img src="${logoUrl}" data-org-name="${org.name}" class="w-full h-full object-contain" />
</div>
<p class="font-bold text-sm truncate">${org.name}</p>
<p class="text-[10px] text-zinc-500 dark:text-zinc-400 font-label uppercase mt-1">${String(org.years)}y · ${org.competition}</p>
<button data-compare-org="${org.name}" class="text-[9px] text-red-500 font-bold uppercase mt-2 hover:underline">Remove</button>
`;
container.appendChild(item);
attachOrgCardListeners(item);
});
// Empty slots helper
for (let i = compareList.length; i < 3; i++) {
const empty = document.createElement('div');
empty.className = 'bg-white dark:bg-zinc-900 rounded-xl p-4 border border-zinc-100 dark:border-zinc-800 border-dashed border-zinc-300 dark:border-zinc-700 flex flex-col items-center justify-center opacity-50';
empty.innerHTML = `
<div class="w-10 h-10 rounded-lg bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center mb-3"><span class="material-symbols-outlined text-zinc-400">add</span></div>
<p class="font-bold text-sm text-zinc-400">Add org</p>
<p class="text-[10px] text-zinc-400 font-label uppercase mt-1">Slot ${i + 1}</p>
`;
container.appendChild(empty);
}
}
function renderCompareModal() {
const body = document.getElementById('compareModalBody');
if (!body) return;
const selectedOrgs = compareList.map(name => ORGS.find(o => o.name === name)).filter(Boolean);
if (selectedOrgs.length < 2) {
body.innerHTML = `
<div class="py-12 text-center border-2 border-dashed border-zinc-200 dark:border-zinc-700 rounded-2xl">
<span class="material-symbols-outlined text-4xl text-zinc-300 dark:text-zinc-600 mb-3">compare_arrows</span>
<p class="font-bold text-zinc-700 dark:text-zinc-300">Select at least 2 organizations to compare.</p>
<p class="text-sm text-zinc-500 dark:text-zinc-400 mt-2">Use the Compare button on organization cards, then open this tool again.</p>
</div>`;
return;
}
const rows = [
['Category', org => getCategoryMeta(org.cat).label],
['GSoC Years', org => org.years],
['First Year', org => org.firstYear],
['Competition', org => org.competition],
['Codebase', org => org.codebase],
['Tech Stack', org => org.tags.join(', ')],
['Best Fit', org => org.fit.join(', ')],
['Repository', org => org.github || '—'],
];
body.innerHTML = `
<table class="w-full min-w-[720px] text-sm">
<thead>