-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
702 lines (605 loc) · 28.1 KB
/
script.js
File metadata and controls
702 lines (605 loc) · 28.1 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
/**
* Shorthand DOM query selectors.
* Reduces boilerplate when interacting with the DOM.
*/
const $ = (s) => document.querySelector(s);
const $$ = (s) => Array.from(document.querySelectorAll(s));
/** Immediately mask elements based on config to prevent UI flashing before network fetches complete */
(function preFetchConfigMasking() {
if (typeof CONFIG === 'undefined') return;
const scholar = CONFIG.contact?.scholar || '';
const li = CONFIG.contact?.linkedin || '';
const mail = CONFIG.contact?.email || '';
const q = (id, show) => { const e = document.getElementById(id); if (e && !show) e.style.display = 'none'; };
q('nav-scholar', CONFIG.display?.header?.scholar && scholar);
q('nav-contact', CONFIG.display?.header?.contact);
q('gh-link', CONFIG.display?.header?.github);
q('contact-scholar', CONFIG.display?.footer?.scholar && scholar);
q('contact-github', CONFIG.display?.footer?.github);
q('contact-linkedin', CONFIG.display?.footer?.linkedin && li);
q('contact-mail', CONFIG.display?.footer?.email && mail);
})();
/**
* Wrapper for native fetch that enforces a timeout.
* Prevents hanging API calls on slow networks.
*
* @param {string} url - Target URL.
* @param {RequestInit} [options={}] - Fetch options.
* @param {number} [ms=15000] - Timeout in milliseconds.
* @returns {Promise<Response>}
*/
function fetchWithTimeout(url, options = {}, ms = 15000) {
const c = new AbortController();
const id = setTimeout(() => c.abort('timeout'), ms);
return fetch(url, { ...options, signal: c.signal }).finally(() => clearTimeout(id));
}
/**
* Builds HTTP headers for GitHub API requests.
* Injects the authorization token safely only for the api.github.com host.
*/
function applyHeaders(url, headers = {}) {
const h = { ...headers, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
try {
const u = new URL(url);
if (u.hostname === 'api.github.com' && CONFIG.githubToken && CONFIG.githubToken.trim()) {
h['Authorization'] = `Bearer ${CONFIG.githubToken.trim()}`;
}
} catch { }
return h;
}
/**
* Formats an ISO date string into a highly readable, compact relative time layout (e.g., '2d ago').
*/
function timeAgo(iso) {
const d = new Date(iso); const s = Math.floor((Date.now() - d) / 1000);
const units = [{ k: 31536000, n: 'yr' }, { k: 2592000, n: 'mo' }, { k: 604800, n: 'w' }, { k: 86400, n: 'd' }, { k: 3600, n: 'h' }, { k: 60, n: 'm' }, { k: 1, n: 's' }];
for (const u of units) { const v = Math.floor(s / u.k); if (v >= 1) return v + u.n + ' ago'; }
return 'just now';
}
/**
* Compact number formatter for large metric counts (e.g., 1.2k, 1M).
*/
function formatNum(n) { if (n >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, '') + 'M'; if (n >= 1e3) return (n / 1e3).toFixed(1).replace(/\.0$/, '') + 'k'; return String(n); }
/**
* Fetches the user profile from GitHub with session-storage hydration to heavily buffer rate limits.
*/
async function fetchUser(username) {
const key = `user:${username}`; try { const c = JSON.parse(sessionStorage.getItem(key) || 'null'); if (c && Date.now() - c.t < CONFIG.cacheTtlMs) return c.v; } catch { }
const url = `https://api.github.com/users/${username}`;
const res = await fetchWithTimeout(url, { headers: applyHeaders(url, {}) }); if (!res.ok) throw new Error('GitHub ' + res.status);
const v = await res.json(); sessionStorage.setItem(key, JSON.stringify({ t: Date.now(), v })); return v;
}
async function fetchRepos(username) {
const key = `repos:${username}`; try { const c = JSON.parse(sessionStorage.getItem(key) || 'null'); if (c && Date.now() - c.t < CONFIG.cacheTtlMs) return c.v; } catch { }
const url = `https://api.github.com/users/${username}/repos?per_page=100&type=owner&sort=updated`;
const res = await fetchWithTimeout(url, { headers: applyHeaders(url, {}) }); if (!res.ok) throw new Error('GitHub ' + res.status);
const repos = await res.json(); repos.sort((a, b) => b.stargazers_count - a.stargazers_count);
sessionStorage.setItem(key, JSON.stringify({ t: Date.now(), v: repos })); return repos;
}
/** Attempts to fetch README (raw) and returns media url + short excerpt. */
const COMMON_READMES = ['README.md', 'Readme.md', 'README.MD', 'README', 'index.md'];
function normalizeImage(raw, base) {
let u = raw.trim().replace(/^<|>$/g, '');
if (!/^https?:\/\//i.test(u)) return base + u.replace(/^\.\//, '');
try {
const url = new URL(u);
if (url.hostname === 'github.com') {
if (/\/blob\//.test(url.pathname)) { url.pathname = url.pathname.replace('/blob/', '/raw/'); url.search = ''; return url.toString(); }
if (/\/assets\//.test(url.pathname) || /user-attachments\/assets\//.test(url.pathname)) { if (!url.searchParams.has('raw')) url.searchParams.set('raw', '1'); return url.toString(); }
}
return url.toString();
} catch { return u; }
}
function isImageish(u) { return /\.(png|jpe?g|gif|webp|svg)(\?|#|$)/i.test(u) || /user-attachments\/assets\//i.test(u) || /\/assets\//.test(u) || /user-images\.githubusercontent\.com/i.test(u); }
function isBadge(u) { return /shields\.io|badgen\.net|badge|coveralls|travis|circleci|codecov|sonarcloud/i.test(u); }
/**Attempts to fetch a repo’s README quickly (tries default branch, then master) and returns text + base URL */
async function fetchReadmeFast(username, repo) {
const branch = repo.default_branch || 'main';
for (const name of COMMON_READMES) {
const raw = `https://raw.githubusercontent.com/${username}/${repo.name}/${branch}/${name}`;
const res = await fetchWithTimeout(raw, {}, 10000);
if (res.ok) { const text = await res.text(); const base = raw.replace(/[^/]+$/, ''); return { text, base }; }
}
if (branch !== 'master') {
for (const name of COMMON_READMES) {
const raw = `https://raw.githubusercontent.com/${username}/${repo.name}/master/${name}`;
const res = await fetchWithTimeout(raw, {}, 10000);
if (res.ok) { const text = await res.text(); const base = raw.replace(/[^/]+$/, ''); return { text, base }; }
}
}
return null;
}
/** Checksif a repo matches a spotlight filter (by language, stars, topics, and optional exclusions) */
function matchesFilter(repo, f) {
if (!f) return true;
const okLang = !f.language || f.language.includes(repo.language);
const okStars = !(f.starsMin >= 0) || (repo.stargazers_count >= f.starsMin);
const okTopics = !f.topics || (Array.isArray(repo.topics) && repo.topics.some(t => f.topics.includes(t)));
const notExcluded =
!f.exclude ||
(
!(f.exclude.names && f.exclude.names.includes(repo.name)) &&
!(f.exclude.topics && Array.isArray(repo.topics) && repo.topics.some(t => f.exclude.topics.includes(t)))
);
return okLang && okStars && okTopics && notExcluded;
}
/** Resolves a spotlight spec: merge explicit repos + filtered repos, sorted by last updated */
function resolveSpotlightSpec(s, repos) {
const explicitNames = (Array.isArray(s.repos) ? s.repos : []).filter(Boolean); // strip '', null, etc.
const hasRepos = explicitNames.length > 0;
const hasFilter = !!(s.filter && Object.keys(s.filter).length);
let combined = [];
if (hasRepos && hasFilter) {
const explicitSet = new Set(explicitNames);
combined = repos.filter(r => explicitSet.has(r.name) || matchesFilter(r, s.filter));
} else if (hasRepos) {
const explicitSet = new Set(explicitNames);
combined = repos.filter(r => explicitSet.has(r.name));
} else if (hasFilter) {
combined = repos.filter(r => matchesFilter(r, s.filter));
} else {
combined = []; // neither repos nor filter → show nothing
}
combined.sort((a, b) => new Date(b.pushed_at) - new Date(a.pushed_at));
return s.limit ? combined.slice(0, s.limit) : combined;
}
/** Fetches a repo’s README, extracts first valid image + short text excerpt, with session caching */
async function readmeMediaAndExcerpt(username, repo) {
const key = `readme_fast:${username}/${repo.name}`; try { const c = JSON.parse(sessionStorage.getItem(key) || 'null'); if (c && Date.now() - c.t < CONFIG.cacheTtlMs) return c.v; } catch { }
const fetched = await fetchReadmeFast(username, repo);
if (!fetched) { const out = { img: null, excerpt: '' }; sessionStorage.setItem(key, JSON.stringify({ t: Date.now(), v: out })); return out; }
const { text, base } = fetched;
let img = null, m;
const mdRe = /!\[[^\]]*\]\(([^)]+)\)/g;
while ((m = mdRe.exec(text)) !== null) {
const n = normalizeImage(m[1], base); if (!isBadge(n) && isImageish(n)) { img = n; break; }
}
if (!img) {
const htmlRe = /<img[^>]+src=[\"']([^\"']+)[\"'][^>]*>/gi;
while ((m = htmlRe.exec(text)) !== null) { const n = normalizeImage(m[1], base); if (!isBadge(n) && isImageish(n)) { img = n; break; } }
}
// first meaningful line as excerpt
let excerpt = pickExcerptFromReadme(text);
const out = { img, excerpt };
sessionStorage.setItem(key, JSON.stringify({ t: Date.now(), v: out }));
return out;
}
/** Grabs tags of repos. */
function extractTagsFromDesc(desc) {
if (!desc) return [];
const out = [];
// [tag] style (ignore common non-tags)
const bad = new Set(['wip', 'archived', 'deprecated', 'beta', 'alpha']);
for (const m of desc.matchAll(/\[([^\]]{1,24})\]/g)) {
const tag = m[1].trim();
if (!bad.has(tag.toLowerCase()) && /[A-Za-z0-9]/.test(tag)) out.push(tag);
}
// #tag style (avoid headings; keep words/numbers/+-.)
for (const m of desc.matchAll(/(^|\s)#([A-Za-z0-9][A-Za-z0-9+_.-]{0,23})\b/g)) {
out.push(m[2]);
}
return out;
}
function getTags(repo, limit = 5) {
const fromTopics = Array.isArray(repo.topics) ? repo.topics.slice(0, limit + 5) : [];
const fromDesc = extractTagsFromDesc(repo.description);
// merge + dedupe, keep order preference: description first, then topics
const seen = new Set(), merged = [];
for (const t of [...fromDesc, ...fromTopics]) {
const k = t.toLowerCase();
if (!seen.has(k)) { seen.add(k); merged.push(t); }
if (merged.length >= limit) break;
}
return merged;
}
/** ignores .md text/image text */
function pickExcerptFromReadme(text) {
// Remove fenced code blocks entirely
text = text.replace(/```[\s\S]*?```/g, '\n');
const lines = text.split(/\r?\n/);
for (let raw of lines) {
let s = raw.trim();
if (!s) continue;
if (/^#/.test(s)) continue;
if (/^!\[/.test(s)) continue;
if (/^<(?:img|p|div|center|h\d|br|hr)\b/i.test(s)) continue;
s = s.replace(/<img[^>]*>/gi, '');
s = s.replace(/<[^>]+>/g, '');
s = s
.replace(/!\[[^\]]*\]\([^)]+\)/g, '') // images
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')// links
.replace(/`([^`]+)`/g, '$1') // code ticks
.replace(/\s+/g, ' ')
.trim();
// Skip badge-y stuff if it slipped through
if (/shields\.io|badgen\.net|badge|travis|circleci|codecov|sonarcloud/i.test(raw)) continue;
if (s) return s.length > 220 ? s.slice(0, 217) + '…' : s;
}
return '';
}
function makeTagsRow(tags) {
if (!tags || !tags.length) return null;
const row = document.createElement('div');
row.className = 'tags';
for (const t of tags) {
const pill = document.createElement('span');
pill.className = 'tag-pill';
pill.textContent = t;
row.appendChild(pill);
}
return row;
}
/** Clean raw GitHub slugs for readability */
function formatTitle(slug) {
return slug.replace(/[-_]+/g, ' ')
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/\b[a-z](?=[a-z]{2})/g, c => c.toUpperCase())
.replace(/w /g, 'w/ ') // Fix common 'w/' pattern
.trim();
}
/** Creates a featured/special card with optional banner and excerpt. */
function card(repo, imgUrl, excerpt) {
const el = document.createElement('article'); el.className = 'card';
if (imgUrl) { const img = document.createElement('img'); img.className = 'banner'; img.alt = `${repo.name} preview`; img.loading = 'lazy'; img.decoding = 'async'; img.src = imgUrl; el.appendChild(img); }
const body = document.createElement('div'); body.className = 'card-body'; el.appendChild(body);
const h = document.createElement('h3'); h.textContent = formatTitle(repo.name); body.appendChild(h);
const p = document.createElement('p'); p.textContent = (excerpt || repo.description || 'No description.'); body.appendChild(p);
const meta = document.createElement('div');
meta.className = 'meta';
const parts = [`★ ${formatNum(repo.stargazers_count)}`];
if (repo.language) parts.push(repo.language);
parts.push(`Updated ${timeAgo(repo.pushed_at)}`);
meta.textContent = parts.join(' · ');
body.appendChild(meta);
const tags = getTags(repo);
const tagsRow = makeTagsRow(tags);
if (tagsRow) body.appendChild(tagsRow);
const links = document.createElement('div'); links.className = 'links';
const a = document.createElement('a'); a.className = 'link'; a.href = repo.html_url; a.target = '_blank'; a.rel = 'noopener'; a.innerHTML = `<svg class="inline-icon"><use href="#i-github"/></svg> Repo`; links.appendChild(a);
if (repo.homepage) { const l = document.createElement('a'); l.className = 'link'; l.href = repo.homepage; l.target = '_blank'; l.rel = 'noopener'; l.innerHTML = `<svg class="inline-icon"><use href="#i-external"/></svg> Live`; links.appendChild(l); }
body.appendChild(links);
return el;
}
/** Renders a horizontal rail with a header and cards. */
async function renderRail(rootEl, title, description, repos) {
rootEl.innerHTML = '';
const head = document.createElement('div');
head.className = 'section-head';
head.innerHTML = `<h2>${title} <span class="section-count">${repos.length}</span></h2><div class="section-desc">${description || ''}</div>`;
const rail = document.createElement('div');
rail.className = 'rail';
const scroller = document.createElement('div');
scroller.className = 'scroller scroller--hero';
rail.appendChild(scroller);
rootEl.appendChild(head);
rootEl.appendChild(rail);
// create skeletons - fast first paint
const frag = document.createDocumentFragment();
const placeholders = repos.map(r => {
const el = card(r, null, r.description || '');
el.classList.add('skeleton-card');
frag.appendChild(el);
return el;
});
scroller.appendChild(frag);
//streaming each card as soon as its README/media is ready
repos.forEach(async (r, i) => {
try {
const { img, excerpt } = await readmeMediaAndExcerpt(CONFIG.username, r);
const old = placeholders[i];
const updated = card(r, img, excerpt || (r.description || 'No description.'));
updated.classList.remove('skeleton-card');
scroller.replaceChild(updated, old);
} catch (e) {
console.error(e);
}
});
}
/** Creates a grid item for the all-projects section. */
function gridItem(repo) {
const el = document.createElement('article'); el.className = 'proj';
if ('startViewTransition' in document) {
el.style.viewTransitionName = 'grid-' + repo.name.replace(/[^a-zA-Z0-9]/g, '');
}
const h = document.createElement('h4'); h.textContent = formatTitle(repo.name); el.appendChild(h);
const d = document.createElement('p'); d.textContent = repo.description || 'No description.'; el.appendChild(d);
const nums = document.createElement('div'); nums.className = 'numbers'; const parts = [`★ ${formatNum(repo.stargazers_count)}`]; if (repo.language) parts.push(repo.language); parts.push(`Updated ${timeAgo(repo.pushed_at)}`); nums.textContent = parts.join(' · '); el.appendChild(nums);
const tags = getTags(repo);
const tagsRow = makeTagsRow(tags);
if (tagsRow) el.appendChild(tagsRow);
const cta = document.createElement('div'); cta.className = 'cta'; const links = document.createElement('div'); links.className = 'links';
const a = document.createElement('a'); a.className = 'link'; a.href = repo.html_url; a.target = '_blank'; a.rel = 'noopener'; a.innerHTML = `<svg class="inline-icon"><use href="#i-github"/></svg> Repo`; links.appendChild(a);
if (repo.homepage) { const l = document.createElement('a'); l.className = 'link'; l.href = repo.homepage; l.target = '_blank'; l.rel = 'noopener'; l.innerHTML = `<svg class="inline-icon"><use href="#i-external"/></svg> Live`; links.appendChild(l); }
cta.appendChild(links); el.appendChild(cta); return el;
}
/** Populates language filter from repo list. */
function populateLangFilter(repos) {
const langs = new Set(); repos.forEach(r => r.language && langs.add(r.language));
const sel = $('#lang'); sel.innerHTML = '<option value="">All languages</option>' + Array.from(langs).sort().map(l => `<option>${l}</option>`).join('');
}
/** Applies search / language / sort transforms to repo list. */
function filterAndSort(repos) {
const qEl = document.querySelector('#q');
const langEl = document.querySelector('#lang');
const sortEl = document.querySelector('#sort');
const q = (qEl?.value || '').toLowerCase().trim();
const lang = (langEl?.value || '');
const sort = (sortEl?.value || 'stars');
const qTerms = q ? q.split(/\s+/).filter(Boolean) : [];
let r = repos.filter(x => {
const name = (x.name || '').toLowerCase();
const desc = (x.description || '').toLowerCase();
const langOk = !lang || x.language === lang;
const qOk = !q || qTerms.every(t => name.includes(t) || desc.includes(t));
return langOk && qOk;
});
const safeDate = d => (d ? new Date(d).getTime() : 0);
switch (sort) {
case 'updated':
r.sort((a, b) =>
safeDate(b.pushed_at) - safeDate(a.pushed_at) ||
(b.stargazers_count - a.stargazers_count) ||
a.name.localeCompare(b.name)
);
break;
case 'name':
r.sort((a, b) => a.name.localeCompare(b.name));
break;
case 'stars':
default:
r.sort((a, b) =>
(b.stargazers_count - a.stargazers_count) ||
(safeDate(b.pushed_at) - safeDate(a.pushed_at)) ||
a.name.localeCompare(b.name)
);
break;
}
return r;
}
/** Paints the all-projects grid with cinematic view transitions. */
function renderGrid(repos) {
const updateDOM = () => {
const grid = $('#grid'); grid.innerHTML = ''; const filtered = filterAndSort(repos);
const countEl = document.getElementById('grid-count');
if (countEl) countEl.textContent = filtered.length;
if (filtered.length === 0) { grid.innerHTML = '<div class="section-desc">No projects match your filters.</div>'; return; }
const frag = document.createDocumentFragment();
filtered.forEach(r => frag.appendChild(gridItem(r)));
grid.appendChild(frag);
};
if (document.startViewTransition && window.matchMedia('(prefers-reduced-motion: no-preference)').matches) {
document.startViewTransition(() => updateDOM());
} else {
updateDOM();
}
}
/** Sets hero branding and contact links from the user object + config. */
function setBrand(user) {
document.title = `${user.name || user.login}'s Portfolio`;
$('#brand-name').textContent = user.name || user.login;
$('#footer-name').textContent = user.name || user.login;
$('#gh-link').href = user.html_url;
const img = $('#avatar');
img.alt = `${user.name || user.login}'s GitHub Avatar`;
img.src = `${user.avatar_url}&s=200`;
img.classList.remove('skeleton');
img.onerror = () => {
const fallback = document.createElement('div');
fallback.className = 'avatar avatar-fallback';
fallback.textContent = (user.name || user.login).substring(0, 2).toUpperCase();
img.replaceWith(fallback);
};
const dn = $('#display-name'); dn.textContent = user.name || user.login; dn.removeAttribute('aria-busy');
const b = $('#bio'); b.textContent = user.bio || ''; b.removeAttribute('aria-busy');
$('#location-pill').textContent = user.location || '—';
if (user.blog) { const bp = $('#blog-pill'); try { bp.textContent = new URL(user.blog).host || user.blog; } catch { bp.textContent = user.blog } bp.style.display = 'inline-flex'; }
$('#since').textContent = `On GitHub since ${new Date(user.created_at).getFullYear()}`;
// contact & display logic
const gh = CONFIG.contact?.github || user.html_url || `https://github.com/${user.login}`;
const li = CONFIG.contact?.linkedin || '';
const mail = CONFIG.contact?.email || '';
const scholar = CONFIG.contact?.scholar || '';
// Header display toggles
const navScholar = document.getElementById('nav-scholar');
if (CONFIG.display?.header?.scholar && scholar) navScholar.href = scholar; else navScholar.style.display = 'none';
const navContact = document.getElementById('nav-contact');
if (!CONFIG.display?.header?.contact) navContact.style.display = 'none';
const navGithub = document.getElementById('gh-link');
if (CONFIG.display?.header?.github) navGithub.href = gh; else navGithub.style.display = 'none';
// Footer display toggles
const footScholar = document.getElementById('contact-scholar');
if (CONFIG.display?.footer?.scholar && scholar) footScholar.href = scholar; else footScholar.style.display = 'none';
const footGithub = document.getElementById('contact-github');
if (CONFIG.display?.footer?.github) footGithub.href = gh; else footGithub.style.display = 'none';
const footLinkedin = document.getElementById('contact-linkedin');
if (CONFIG.display?.footer?.linkedin && li) footLinkedin.href = li; else footLinkedin.style.display = 'none';
const footMail = document.getElementById('contact-mail');
if (CONFIG.display?.footer?.email && mail) footMail.href = mail; else footMail.style.display = 'none';
// about
if (CONFIG.about?.html) { document.getElementById('about-content').innerHTML = CONFIG.about.html; }
}
/** Main bootstrap: api calls, then build UI. */
async function main() {
document.getElementById('year').textContent = new Date().getFullYear();
try {
const [user, repos] = await Promise.all([
fetchUser(CONFIG.username),
fetchRepos(CONFIG.username)
]);
setBrand(user);
document.getElementById('repo-count').textContent = repos.length;
const totalStars = repos.reduce((a, r) => a + r.stargazers_count, 0);
document.getElementById('total-stars').textContent = formatNum(totalStars);
populateLangFilter(repos);
renderGrid(repos);
const qEl = document.getElementById('q');
const langEl = document.getElementById('lang');
const sortEl = document.getElementById('sort');
let tId = null;
qEl?.addEventListener('input', () => {
clearTimeout(tId);
tId = setTimeout(() => renderGrid(repos), 200);
});
langEl?.addEventListener('change', () => renderGrid(repos));
sortEl?.addEventListener('change', () => renderGrid(repos));
// --- Featured ---
const featuredRepos = (CONFIG.featured?.repos || []).map(name => repos.find(r => r.name === name)).filter(Boolean);
const featuredSection = document.getElementById('featured-section');
if (featuredRepos.length > 0) {
// kick off async render; don't await (skeletons show immediately)
renderRail(
featuredSection,
CONFIG.featured?.title || 'Featured',
CONFIG.featured?.description || '',
featuredRepos
).catch(console.error);
} else if (featuredSection) {
featuredSection.style.display = 'none';
}
// --- Spotlights ---
const spotRoot = document.getElementById('spotlights');
spotRoot.innerHTML = '';
for (const s of (CONFIG.spotlights || [])) {
const list = resolveSpotlightSpec(s, repos);
if (!list.length) continue;
const wrap = document.createElement('section');
// attach first so skeletons can paint right away
spotRoot.appendChild(wrap);
// kick off async render; don't await
renderRail(
wrap,
s.title || 'Spotlight',
s.description || '',
list
).catch(console.error);
}
} catch (e) {
console.error(e);
const dn = document.getElementById('display-name');
if (dn) { dn.textContent = 'Profile Unavailable'; dn.removeAttribute('aria-busy'); }
const b = document.getElementById('bio');
if (b) { b.textContent = 'System encountered an error. ' + e.message; b.removeAttribute('aria-busy'); }
const grid = document.getElementById('grid');
if (grid) {
grid.style.display = 'block';
grid.innerHTML = `<div class="error-fallback">
<h3>Repository Data Unavailable</h3>
<p>Failed to load open-source projects from GitHub's API. Please verify your connection or wait for rate-limits to reset.</p>
<button class="btn" style="margin-top: 16px;" onclick="sessionStorage.clear(); location.reload();">Retry Connection</button>
</div>`;
}
}
}
document.addEventListener('DOMContentLoaded', main);
/** Global keyboard shortcut to focus search (/) */
document.addEventListener('keydown', (e) => {
if (e.key === '/' && document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA') {
const qEl = document.getElementById('q');
if (qEl) {
e.preventDefault();
qEl.focus();
// Smooth scroll to the search bar so the user knows they are focused
qEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
});
/** ──────────── ⚡ OVERDRIVE: GENERATIVE CANVAS ───────────── */
(function initAmbientBackground() {
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
const canvas = document.createElement('canvas');
canvas.className = 'ambient-bg';
document.body.prepend(canvas);
const ctx = canvas.getContext('2d', { alpha: true });
let w, h;
const nodes = [];
const MAX_NODES = window.innerWidth > 768 ? 60 : 30;
const CONNECTION_DISTANCE = 160;
const primaryRgb = '98, 224, 255'; // Cyan
const accentRgb = '192, 132, 252'; // Purple
function resize() {
w = canvas.width = window.innerWidth;
h = canvas.height = window.innerHeight;
}
window.addEventListener('resize', resize);
resize();
class Node {
constructor() {
this.x = Math.random() * w;
this.y = Math.random() * h;
this.vx = (Math.random() - 0.5) * 0.4;
this.vy = (Math.random() - 0.5) * 0.4;
this.baseRadius = Math.random() * 1.5 + 0.8;
this.radius = this.baseRadius;
this.type = Math.random() > 0.5 ? 'primary' : 'accent';
}
update() {
this.x += this.vx;
this.y += this.vy;
if (this.x < 0 || this.x > w) this.vx *= -1;
if (this.y < 0 || this.y > h) this.vy *= -1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = `rgba(${this.type === 'primary' ? primaryRgb : accentRgb}, ${0.5 + this.radius * 0.1})`;
ctx.fill();
}
}
for (let i = 0; i < MAX_NODES; i++) nodes.push(new Node());
let mouse = { x: -1000, y: -1000, vx: 0, vy: 0 };
let lastMouse = { x: -1000, y: -1000 };
window.addEventListener('mousemove', (e) => {
mouse.x = e.clientX;
mouse.y = e.clientY;
});
function render(time) {
mouse.vx = mouse.x - lastMouse.x;
mouse.vy = mouse.y - lastMouse.y;
lastMouse.x = mouse.x;
lastMouse.y = mouse.y;
ctx.clearRect(0, 0, w, h);
// Slight blend mode for glowing effect
ctx.globalCompositeOperation = 'screen';
for (let i = 0; i < nodes.length; i++) {
const n1 = nodes[i];
n1.update();
const dx = n1.x - mouse.x;
const dy = n1.y - mouse.y;
const dist = Math.sqrt(dx * dx + dy * dy);
// Spring reaction to mouse physics
if (dist < 180) {
const force = (1 - dist / 180);
n1.x += mouse.vx * force * 0.08;
n1.y += mouse.vy * force * 0.08;
n1.radius = n1.baseRadius + force * 2.5;
} else {
n1.radius = n1.baseRadius;
}
n1.draw();
for (let j = i + 1; j < nodes.length; j++) {
const n2 = nodes[j];
const nx = n1.x - n2.x;
const ny = n1.y - n2.y;
const ndist = Math.sqrt(nx * nx + ny * ny);
if (ndist < CONNECTION_DISTANCE) {
const alpha = 1 - (ndist / CONNECTION_DISTANCE);
ctx.beginPath();
ctx.moveTo(n1.x, n1.y);
ctx.lineTo(n2.x, n2.y);
// Mixed interpolation line (primary to accent looks like blending)
const isMixed = n1.type !== n2.type;
if (isMixed) {
ctx.strokeStyle = `rgba(145, 178, 253, ${alpha * 0.4})`; // Blended middle point
} else {
ctx.strokeStyle = `rgba(${n1.type === 'primary' ? primaryRgb : accentRgb}, ${alpha * 0.35})`;
}
ctx.lineWidth = 0.8 + alpha;
ctx.stroke();
}
}
}
ctx.globalCompositeOperation = 'source-over';
requestAnimationFrame(render);
}
requestAnimationFrame(render);
})();