-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
625 lines (513 loc) · 20.4 KB
/
main.js
File metadata and controls
625 lines (513 loc) · 20.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
const METRICS_CONFIG = {
authorName: 'Mainak Majumder',
orcid: 'https://orcid.org/0009-0008-3062-4793',
openAlexAuthorId: '',
semanticScholarAuthorId: '150219982',
};
function normalizeName(name) {
return (name || '').toLowerCase().replace(/\s+/g, ' ').trim();
}
function extractOrcidId(value) {
if (!value) return '';
const clean = String(value).trim();
const match = clean.match(/(\d{4}-\d{4}-\d{4}-[\dX]{4})/i);
return match ? match[1].toUpperCase() : clean.replace(/^https?:\/\/orcid\.org\//i, '');
}
function formatMetricNumber(value) {
return Number.isFinite(value) ? value.toLocaleString() : 'N/A';
}
function setText(id, value) {
const el = document.getElementById(id);
if (el) el.textContent = value;
}
function setMetricsStatus(value, state) {
const el = document.getElementById('metrics-status');
if (!el) return;
el.textContent = value;
el.classList.remove('is-loading', 'is-live', 'is-partial', 'is-unavailable');
el.classList.add(`is-${state}`);
}
function setLink(id, url) {
const el = document.getElementById(id);
if (!el) return;
if (url) {
el.href = url;
el.style.display = '';
} else {
el.removeAttribute('href');
el.style.display = 'none';
}
}
function semanticScholarFallbackUrl(authorName) {
const q = encodeURIComponent(authorName || METRICS_CONFIG.authorName || '');
return `https://www.semanticscholar.org/search?q=${q}`;
}
function scoreAuthorCandidate(authorName, candidateName, affiliationText = '') {
const target = normalizeName(authorName);
const candidate = normalizeName(candidateName);
const affiliation = normalizeName(affiliationText);
let score = 0;
if (!candidate) return score;
if (candidate === target) score += 10;
if (candidate.includes(target) || target.includes(candidate)) score += 4;
if (affiliation.includes('kepler') || affiliation.includes('linz')) score += 2;
return score;
}
async function fetchJsonWithTimeout(url, timeoutMs = 12000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(url, {
signal: controller.signal,
headers: { Accept: 'application/json' },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} finally {
clearTimeout(timer);
}
}
async function fetchOpenAlexMetrics() {
const cfg = METRICS_CONFIG;
const orcidId = extractOrcidId(cfg.orcid);
let author = null;
if (cfg.openAlexAuthorId) {
author = await fetchJsonWithTimeout(`https://api.openalex.org/authors/${encodeURIComponent(cfg.openAlexAuthorId)}`);
} else if (orcidId) {
author = await fetchJsonWithTimeout(`https://api.openalex.org/authors/orcid:${encodeURIComponent(orcidId)}`);
} else {
const data = await fetchJsonWithTimeout(`https://api.openalex.org/authors?search=${encodeURIComponent(cfg.authorName)}&per-page=10`);
const results = Array.isArray(data?.results) ? data.results : [];
author = results
.map((a) => {
const affiliation = Array.isArray(a?.affiliations) ? a.affiliations.map((x) => x?.institution?.display_name || '').join(' ') : '';
return { a, score: scoreAuthorCandidate(cfg.authorName, a?.display_name, affiliation) };
})
.sort((x, y) => y.score - x.score)[0]?.a || null;
}
if (!author) throw new Error('No OpenAlex author match');
return {
name: author.display_name || cfg.authorName,
citations: Number(author.cited_by_count),
hIndex: Number(author.summary_stats?.h_index),
i10Index: Number(author.summary_stats?.i10_index),
url: author.id || '',
};
}
async function fetchSemanticScholarMetrics() {
const cfg = METRICS_CONFIG;
let author = null;
const coreFields = 'authorId,name,citationCount,hIndex,url,affiliations';
if (cfg.semanticScholarAuthorId) {
try {
author = await fetchJsonWithTimeout(
`https://api.semanticscholar.org/graph/v1/author/${encodeURIComponent(cfg.semanticScholarAuthorId)}?fields=${encodeURIComponent(coreFields)}`
);
} catch (_err) {
author = null;
}
}
if (!author) {
let data = await fetchJsonWithTimeout(
`https://api.semanticscholar.org/graph/v1/author/search?query=${encodeURIComponent(cfg.authorName)}&limit=10&fields=${encodeURIComponent(coreFields)}`
);
let results = Array.isArray(data?.data) ? data.data : [];
author = results
.map((a) => {
const affiliation = Array.isArray(a?.affiliations) ? a.affiliations.join(' ') : '';
return { a, score: scoreAuthorCandidate(cfg.authorName, a?.name, affiliation) };
})
.sort((x, y) => y.score - x.score)[0]?.a || null;
}
if (!author) throw new Error('No Semantic Scholar author match');
const authorId = author.authorId || cfg.semanticScholarAuthorId || '';
let derivedI10 = NaN;
if (authorId) {
try {
const papersData = await fetchJsonWithTimeout(
`https://api.semanticscholar.org/graph/v1/author/${encodeURIComponent(authorId)}/papers?fields=citationCount&limit=1000`
);
const papers = Array.isArray(papersData?.data) ? papersData.data : [];
derivedI10 = papers.filter((p) => Number(p?.citationCount) >= 10).length;
} catch (_err) {
derivedI10 = NaN;
}
}
return {
name: author.name || cfg.authorName,
citations: Number(author.citationCount),
hIndex: Number(author.hIndex),
i10Index: Number.isFinite(derivedI10) ? derivedI10 : NaN,
url: author.url || (authorId ? `https://www.semanticscholar.org/author/${encodeURIComponent(authorId)}` : semanticScholarFallbackUrl(author.name || cfg.authorName)),
};
}
async function loadResearchMetrics() {
const block = document.getElementById('research-metrics');
if (!block) return;
setMetricsStatus('Loading...', 'loading');
const [oaResult, ssResult] = await Promise.allSettled([
fetchOpenAlexMetrics(),
fetchSemanticScholarMetrics(),
]);
const oa = oaResult.status === 'fulfilled' ? oaResult.value : null;
const ss = ssResult.status === 'fulfilled' ? ssResult.value : null;
setText('oa-citations', formatMetricNumber(oa?.citations));
setText('oa-hindex', formatMetricNumber(oa?.hIndex));
setText('oa-i10index', formatMetricNumber(oa?.i10Index));
setLink('oa-link', oa?.url || '');
setText('ss-citations', formatMetricNumber(ss?.citations));
setText('ss-hindex', formatMetricNumber(ss?.hIndex));
setText('ss-i10index', formatMetricNumber(ss?.i10Index));
setLink('ss-link', ss?.url || semanticScholarFallbackUrl(ss?.name));
if (oa && ss) {
setMetricsStatus('Live', 'live');
} else if (oa || ss) {
setMetricsStatus('Partial', 'partial');
} else {
setMetricsStatus('Unavailable', 'unavailable');
}
}
function normalizeText(value) {
return String(value || '')
.toLowerCase()
.replace(/[^a-z0-9\s]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
function scoreWorkTitleCandidate(targetTitle, candidateTitle) {
const target = normalizeText(targetTitle);
const candidate = normalizeText(candidateTitle);
if (!target || !candidate) return 0;
if (target === candidate) return 100;
const targetTokens = new Set(target.split(' ').filter((t) => t.length > 2));
const candidateTokens = new Set(candidate.split(' ').filter((t) => t.length > 2));
let overlap = 0;
targetTokens.forEach((token) => {
if (candidateTokens.has(token)) overlap += 1;
});
const coverage = targetTokens.size ? overlap / targetTokens.size : 0;
return Math.round(coverage * 100);
}
async function fetchOpenAlexWorkCitations({ doi = '', title = '' }) {
const cleanDoi = String(doi || '').trim().replace(/^https?:\/\/doi\.org\//i, '');
const cleanTitle = String(title || '').trim();
if (cleanDoi) {
try {
const doiUri = `https://doi.org/${cleanDoi}`;
const work = await fetchJsonWithTimeout(`https://api.openalex.org/works/${encodeURIComponent(doiUri)}`);
const citations = Number(work?.cited_by_count);
if (Number.isFinite(citations)) return citations;
} catch (_err) {
// Fall back to title search below.
}
}
if (!cleanTitle) return NaN;
const data = await fetchJsonWithTimeout(`https://api.openalex.org/works?search=${encodeURIComponent(cleanTitle)}&per-page=10`);
const results = Array.isArray(data?.results) ? data.results : [];
const best = results
.map((work) => ({
work,
score: scoreWorkTitleCandidate(cleanTitle, work?.display_name || ''),
}))
.sort((a, b) => b.score - a.score)[0];
if (!best || best.score < 55) return NaN;
const citations = Number(best.work?.cited_by_count);
return Number.isFinite(citations) ? citations : NaN;
}
async function loadPublicationCitations() {
const items = Array.from(document.querySelectorAll('#publications .ieeeItem'));
if (items.length === 0) return;
await Promise.all(items.map(async (item) => {
const citeEl = item.querySelector('.ieeeCite');
if (!citeEl) return;
const citeValueEl = citeEl.querySelector('.ieeeCiteValue') || citeEl;
const doi = item.getAttribute('data-doi') || '';
const title = item.getAttribute('data-title') || '';
try {
const citations = await fetchOpenAlexWorkCitations({ doi, title });
if (Number.isFinite(citations)) {
citeValueEl.textContent = `${citations.toLocaleString()}`;
citeEl.classList.add('is-live');
} else {
citeValueEl.textContent = 'Not available';
citeEl.classList.remove('is-live');
}
} catch (_err) {
citeValueEl.textContent = 'Not available';
citeEl.classList.remove('is-live');
}
}));
}
async function loadSections() {
const slots = Array.from(document.querySelectorAll('[data-include]'));
await Promise.all(slots.map(async (slot) => {
const file = slot.getAttribute('data-include');
try {
const res = await fetch(file, { cache: 'no-store' });
if (!res.ok) throw new Error(`Failed to load ${file}: ${res.status}`);
const html = await res.text();
const tpl = document.createElement('template');
tpl.innerHTML = html.trim();
slot.replaceWith(tpl.content);
} catch (err) {
console.error(err);
slot.outerHTML = `
<section class="card">
<h2>Section load error</h2>
<p class="muted" style="margin:0;">Could not load <code>${file}</code>.</p>
</section>
`;
}
}));
}
function monthIndexFromToken(token) {
const match = String(token || '').trim().match(/^(0?[1-9]|1[0-2])[\/.-](\d{4})$/);
if (!match) return null;
const month = Number(match[1]) - 1;
const year = Number(match[2]);
return (year * 12) + month;
}
function isCurrentTimelineRange(dateText, nowIndex) {
if (!dateText) return false;
const tokens = Array.from(String(dateText).matchAll(/\b(0?[1-9]|1[0-2])[\/.-](\d{4})\b/g))
.map((m) => monthIndexFromToken(`${m[1]}/${m[2]}`))
.filter((v) => Number.isFinite(v));
if (tokens.length === 0) return false;
if (/\b(present|current|now)\b/i.test(dateText)) {
return nowIndex >= tokens[0];
}
if (tokens.length === 1) {
return nowIndex === tokens[0];
}
const start = Math.min(tokens[0], tokens[1]);
const end = Math.max(tokens[0], tokens[1]);
return nowIndex >= start && nowIndex <= end;
}
function syncTimelineDots() {
const now = new Date();
const nowIndex = (now.getFullYear() * 12) + now.getMonth();
const items = Array.from(document.querySelectorAll('.timelineItem'));
items.forEach((item) => {
const dateText = item.querySelector('.timelineDate')?.textContent?.trim() || '';
const dot = item.querySelector('.timelineDot');
if (!dot) return;
dot.classList.toggle('is-current', isCurrentTimelineRange(dateText, nowIndex));
});
}
function attachSkillLogos() {
const chips = Array.from(document.querySelectorAll('#about .chip[data-logo]'));
chips.forEach((chip) => {
const slug = chip.getAttribute('data-logo')?.trim();
if (!slug || chip.querySelector('.chipLogo')) return;
const img = document.createElement('img');
img.className = 'chipLogo';
img.alt = '';
img.loading = 'lazy';
img.decoding = 'async';
img.src = `https://cdn.simpleicons.org/${encodeURIComponent(slug)}/173F5F`;
img.addEventListener('error', () => {
chip.classList.remove('has-logo');
img.remove();
});
chip.prepend(img);
chip.classList.add('has-logo');
});
}
function attachProjectTechIcons() {
const items = Array.from(document.querySelectorAll('.projTopics:not(.projTopicsPlain) li'));
function prependFallbackIcon(item) {
if (item.querySelector('.projTechIcon') || item.querySelector('.projTechLogo')) return;
const iconClass = item.getAttribute('data-fallback-icon')?.trim() || 'ph-cpu';
const icon = document.createElement('i');
icon.className = `ph ${iconClass} projTechIcon`;
icon.setAttribute('aria-hidden', 'true');
item.prepend(icon);
}
items.forEach((item) => {
const slug = item.getAttribute('data-logo')?.trim();
if (!slug) {
prependFallbackIcon(item);
return;
}
if (item.querySelector('.projTechLogo') || item.querySelector('.projTechIcon')) return;
const img = document.createElement('img');
img.className = 'projTechLogo';
img.alt = '';
img.loading = 'lazy';
img.decoding = 'async';
img.src = `https://cdn.simpleicons.org/${encodeURIComponent(slug)}/173F5F`;
img.addEventListener('error', () => {
img.remove();
prependFallbackIcon(item);
});
item.prepend(img);
});
}
function boldPublicationTitles() {
const items = Array.from(document.querySelectorAll('#publications .ieeeItem'));
items.forEach((item) => {
const title = item.getAttribute('data-title')?.trim();
const refEl = item.querySelector('.ieeeRef');
if (!title || !refEl) return;
const alreadyBold = refEl.querySelector('strong')?.textContent?.includes(title);
if (alreadyBold) return;
const escapedTitle = title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const withStraightQuotes = new RegExp(`"${escapedTitle}"`, 'g');
const withCurlyQuotes = new RegExp(`“${escapedTitle}”`, 'g');
const plainTitle = new RegExp(escapedTitle, 'g');
if (withStraightQuotes.test(refEl.innerHTML)) {
refEl.innerHTML = refEl.innerHTML.replace(withStraightQuotes, `"<strong>${title}</strong>"`);
return;
}
if (withCurlyQuotes.test(refEl.innerHTML)) {
refEl.innerHTML = refEl.innerHTML.replace(withCurlyQuotes, `“<strong>${title}</strong>”`);
return;
}
refEl.innerHTML = refEl.innerHTML.replace(plainTitle, `<strong>${title}</strong>`);
});
}
function initPublicationPager() {
const section = document.getElementById('publications');
if (!section) return;
const pages = Array.from(section.querySelectorAll('.pubPage'));
if (pages.length <= 1) return;
const prevBtn = section.querySelector('#pub-prev');
const nextBtn = section.querySelector('#pub-next');
const infoEl = section.querySelector('#pub-page-info');
if (!prevBtn || !nextBtn || !infoEl) return;
let activeIndex = pages.findIndex((page) => !page.hasAttribute('hidden'));
if (activeIndex < 0) activeIndex = 0;
function renderPager() {
pages.forEach((page, index) => {
const isActive = index === activeIndex;
page.hidden = !isActive;
page.classList.toggle('is-active', isActive);
});
infoEl.textContent = `Page ${activeIndex + 1} of ${pages.length}`;
prevBtn.disabled = activeIndex === 0;
nextBtn.disabled = activeIndex === pages.length - 1;
}
prevBtn.addEventListener('click', () => {
if (activeIndex <= 0) return;
activeIndex -= 1;
renderPager();
section.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
nextBtn.addEventListener('click', () => {
if (activeIndex >= pages.length - 1) return;
activeIndex += 1;
renderPager();
section.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
renderPager();
}
function initAcademiaPager() {
const section = document.getElementById('academia');
if (!section) return;
const pages = Array.from(section.querySelectorAll('.acadPage'));
if (pages.length <= 1) return;
const prevBtn = section.querySelector('#acad-prev');
const nextBtn = section.querySelector('#acad-next');
const infoEl = section.querySelector('#acad-page-info');
if (!prevBtn || !nextBtn || !infoEl) return;
let activeIndex = pages.findIndex((page) => !page.hasAttribute('hidden'));
if (activeIndex < 0) activeIndex = 0;
function renderPager() {
pages.forEach((page, index) => {
const isActive = index === activeIndex;
page.hidden = !isActive;
page.classList.toggle('is-active', isActive);
});
infoEl.textContent = `Page ${activeIndex + 1} of ${pages.length}`;
prevBtn.disabled = activeIndex === 0;
nextBtn.disabled = activeIndex === pages.length - 1;
}
prevBtn.addEventListener('click', () => {
if (activeIndex <= 0) return;
activeIndex -= 1;
renderPager();
section.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
nextBtn.addEventListener('click', () => {
if (activeIndex >= pages.length - 1) return;
activeIndex += 1;
renderPager();
section.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
renderPager();
}
function getActivePanel() {
return document.querySelector('.tabPanel.is-active');
}
function getPanelIdFromHash() {
return window.location.hash ? window.location.hash.slice(1) : '';
}
function activateTab(panelId, options = {}) {
const { syncHash = true } = options;
const tabs = Array.from(document.querySelectorAll('.tabBtn'));
const panels = Array.from(document.querySelectorAll('.tabPanel'));
const hasTarget = panels.some((panel) => panel.id === panelId);
if (!hasTarget) return;
tabs.forEach((tab) => {
const isActive = tab.getAttribute('data-tab-target') === panelId;
tab.classList.toggle('is-active', isActive);
tab.setAttribute('aria-selected', String(isActive));
tab.tabIndex = isActive ? 0 : -1;
});
panels.forEach((panel) => {
const isActive = panel.id === panelId;
panel.classList.toggle('is-active', isActive);
panel.hidden = !isActive;
});
if (syncHash) {
history.replaceState(null, '', `#${panelId}`);
}
}
function initTabs() {
const tabs = Array.from(document.querySelectorAll('.tabBtn'));
tabs.forEach((tab, index) => {
tab.tabIndex = tab.classList.contains('is-active') ? 0 : -1;
tab.addEventListener('click', () => {
activateTab(tab.getAttribute('data-tab-target'));
});
tab.addEventListener('keydown', (e) => {
let nextIndex = index;
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') nextIndex = (index + 1) % tabs.length;
if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') nextIndex = (index - 1 + tabs.length) % tabs.length;
if (e.key === 'Home') nextIndex = 0;
if (e.key === 'End') nextIndex = tabs.length - 1;
if (nextIndex !== index) {
e.preventDefault();
tabs[nextIndex].focus();
tabs[nextIndex].click();
}
});
});
}
function initPageUi() {
const updated = document.getElementById('updated');
updated.textContent = new Date().toLocaleDateString(undefined, { year:'numeric', month:'long', day:'numeric' });
initTabs();
const panelIdFromHash = getPanelIdFromHash();
if (panelIdFromHash) {
activateTab(panelIdFromHash, { syncHash: false });
}
window.addEventListener('hashchange', () => {
const panelId = getPanelIdFromHash();
if (panelId) activateTab(panelId, { syncHash: false });
});
}
document.addEventListener('DOMContentLoaded', async () => {
await loadSections();
attachSkillLogos();
attachProjectTechIcons();
boldPublicationTitles();
syncTimelineDots();
initPublicationPager();
initAcademiaPager();
await Promise.allSettled([
loadResearchMetrics(),
loadPublicationCitations(),
]);
initPageUi();
});