-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
788 lines (679 loc) · 32 KB
/
script.js
File metadata and controls
788 lines (679 loc) · 32 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
// Wrap in IIFE to avoid const conflicts with inline scripts
(function() {
"use strict";
const themeToggle = document.getElementById('theme-toggle');
const body = document.body;
const root = document.documentElement;
// Function to parse CSS color to RGB array
function colorToRgb(color) {
if (!color) return [255, 255, 255]; // Default fallback
if (color.startsWith('#')) {
const bigint = parseInt(color.slice(1), 16);
const r = (bigint >> 16) & 255;
const g = (bigint >> 8) & 255;
const b = bigint & 255;
return [r, g, b];
} else if (color.startsWith('rgb')) {
const match = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
return match ? [parseInt(match[1]), parseInt(match[2]), parseInt(match[3])] : [255, 255, 255];
}
// Basic named color handling (add more if needed)
if (color === 'white') return [255, 255, 255];
if (color === 'black') return [0, 0, 0];
return [255, 255, 255];
}
// Function to update RGB CSS variables based on current theme
function updateRgbVariables() {
const computedStyle = getComputedStyle(root);
const bgColor = computedStyle.getPropertyValue('--bg-color').trim();
const accentColor = computedStyle.getPropertyValue('--accent-color').trim();
const bgRgb = colorToRgb(bgColor).join(', ');
const accentRgb = colorToRgb(accentColor).join(', ');
root.style.setProperty('--bg-color-rgb', bgRgb);
root.style.setProperty('--accent-color-rgb', accentRgb);
}
// Function to apply the theme
function applyTheme(theme) {
if (theme === 'dark') {
body.classList.add('dark-theme');
} else {
body.classList.remove('dark-theme');
}
// Update RGB variables after theme change
updateRgbVariables();
}
// Function to toggle theme and save preference
function toggleTheme() {
let currentTheme = body.classList.contains('dark-theme') ? 'dark' : 'light';
let newTheme = currentTheme === 'dark' ? 'light' : 'dark';
localStorage.setItem('theme', newTheme);
applyTheme(newTheme);
}
// Event listener for the button
if (themeToggle) themeToggle.addEventListener('click', toggleTheme);
// Apply saved theme on initial load
document.addEventListener('DOMContentLoaded', () => {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const savedTheme = localStorage.getItem('theme') || (prefersDark ? 'dark' : 'light');
applyTheme(savedTheme); // Apply theme first
// Fetch GitHub data
setupScrollReveal(); // Setup scroll animations
setupScrollSpy(); // Setup scroll spy for nav
setupMarquee(); // Setup infinite marquee
fetchGitHubProfile();
fetchGitHubRepos();
fetchGitHubActivity();
// Update indicators after all fetches are attempted
fetchAllGitHubDataAndUpdateIndicators();
});
// --- Scroll Spy Function ---
function setupScrollSpy() {
const sections = document.querySelectorAll('section');
const navLinks = document.querySelectorAll('nav ul li a');
const observerOptions = {
root: null,
rootMargin: '0px',
threshold: 0.3 // Trigger when 30% of section is visible
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const id = entry.target.getAttribute('id');
navLinks.forEach(link => {
link.classList.remove('active');
if (link.getAttribute('href') === `#${id}`) {
link.classList.add('active');
}
});
}
});
}, observerOptions);
sections.forEach(section => {
observer.observe(section);
});
}
// --- Marquee Setup ---
function setupMarquee() {
const marqueeContent = document.querySelector('.marquee-content');
if (marqueeContent) {
// Clone content to ensure seamless scrolling
const clone = marqueeContent.cloneNode(true);
marqueeContent.parentNode.appendChild(clone);
}
}
// --- Scroll Reveal Function ---
function setupScrollReveal() {
const revealElements = document.querySelectorAll('.reveal');
const observerOptions = {
root: null, // relative to document viewport
rootMargin: '0px',
threshold: 0.1 // trigger when 10% of the element is visible
};
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('is-visible');
// Optional: Unobserve after revealing to save resources
// observer.unobserve(entry.target);
}
// Optional: Remove class if element scrolls out of view (for re-revealing)
// else {
// entry.target.classList.remove('is-visible');
// }
});
}, observerOptions);
revealElements.forEach(el => {
observer.observe(el);
});
}
// --- GitHub Data Fetching Orchestration ---
async function fetchAllGitHubDataAndUpdateIndicators() {
console.log('Initiating GitHub data fetches...');
// Store initial HTML content before potential updates
captureInitialValues();
// Run all fetch functions concurrently and wait for all to settle
const results = await Promise.allSettled([
fetchGitHubProfile(),
fetchGitHubRepos(),
fetchGitHubActivity()
]);
console.log('GitHub fetch results:', results);
// Determine overall status for stats and activity
const profileResult = results[0];
const repoResult = results[1];
const activityResult = results[2];
let statsStatus = 'failed';
let statsExpiry = null;
if (profileResult.status === 'fulfilled' && repoResult.status === 'fulfilled') {
if (profileResult.value.status === 'live' && repoResult.value.status === 'live') {
statsStatus = 'live';
} else if (profileResult.value.status === 'cached' || repoResult.value.status === 'cached') {
statsStatus = 'cached';
// Use the earliest expiry time if multiple caches were hit
statsExpiry = Math.min(
profileResult.value.expiry || Infinity,
repoResult.value.expiry || Infinity
);
}
}
let activityStatus = activityResult.status === 'fulfilled' ? activityResult.value.status : 'failed';
let activityExpiry = activityResult.status === 'fulfilled' ? activityResult.value.expiry : null;
console.log(`Final Status - Stats: ${statsStatus}, Activity: ${activityStatus}`);
// Update UI indicators (opacity and tooltips)
updateDataIndicators('stats', statsStatus, statsExpiry);
updateDataIndicators('activity', activityStatus, activityExpiry);
}
function captureInitialValues() {
// Capture initial stat values (example for stars)
const starsElement = document.querySelector('.stat-number[data-stat="stars"]');
if (starsElement) initialStats.stars = starsElement.textContent;
// Capture initial project details (if needed for better fallback)
// const projectItems = document.querySelectorAll('#projects .item');
// projectItems.forEach(item => { ... });
}
function updateDataIndicators(section, status, expiry) {
const element = document.querySelector(section === 'stats' ? '.github-stats' : '.activity-feed');
if (!element) return;
let tooltipText = `GitHub ${section === 'stats' ? 'Stats' : 'Activity'}: `;
element.classList.remove('data-stale'); // Reset state
switch (status) {
case 'live':
tooltipText += 'Live data.';
break;
case 'cached':
element.classList.add('data-stale');
tooltipText += 'Cached data';
if (expiry) {
const now = new Date().getTime();
const ageMinutes = Math.round((now - (expiry - 3600000)) / 60000); // Calculate age based on when it was set
tooltipText += ` (approx. ${ageMinutes} min ago).`;
} else {
tooltipText += '.';
}
break;
case 'failed':
default:
element.classList.add('data-stale');
tooltipText += 'Update failed; showing defaults or cached data.';
break;
}
element.setAttribute('title', tooltipText);
}
// GitHub API functions (mostly unchanged, just formatting adjustments)
const githubUsername = 'ipv1337';
async function fetchGitHubProfile() {
const cacheKey = 'githubProfileData';
const cachedData = cache.get(cacheKey);
if (cachedData) {
console.log('Using cached GitHub profile data.');
updateGitHubStats(cachedData);
return { status: 'cached', data: cachedData };
}
console.log('Fetching fresh GitHub profile data...');
try {
const response = await fetch(`https://api.github.com/users/${githubUsername}`);
if (!response.ok) throw new Error(`GitHub API error: ${response.statusText}`);
const data = await response.json();
updateGitHubStats(data);
cache.set(cacheKey, data); // Cache the fresh data
return { status: 'live', data: data };
} catch (error) {
console.error('Error fetching GitHub profile:', error);
// Return status even on failure
return { status: 'failed', data: null };
}
}
// Helper function to manage cache
const cache = {
get: (key) => {
const itemStr = localStorage.getItem(key);
if (!itemStr) return null;
try {
const item = JSON.parse(itemStr);
const now = new Date();
// Check if item expired (e.g., older than 1 hour)
if (now.getTime() > item.expiry) {
localStorage.removeItem(key); // Remove expired item
return null;
}
// Return both value and expiry time
return { value: item.value, expiry: item.expiry };
} catch (e) {
console.error('Error reading from localStorage:', e);
localStorage.removeItem(key); // Remove corrupted item
return null;
}
},
set: (key, value, ttl = 3600000) => { // Default TTL: 1 hour (in milliseconds)
const now = new Date();
const item = {
value: value,
expiry: now.getTime() + ttl,
};
try {
localStorage.setItem(key, JSON.stringify(item));
} catch (e) {
console.error('Error writing to localStorage:', e);
// Consider clearing some old cache items if storage is full
}
}
};
function updateGitHubStats(data) {
// Ensure data exists before updating
if (!data) return;
// Update specific stats, falling back to '...' if data is missing fields
const statsToUpdate = {
repos: data.public_repos,
followers: data.followers,
following: data.following,
};
for (const [key, value] of Object.entries(statsToUpdate)) {
const element = document.querySelector(`.stat-number[data-stat="${key}"]`);
// Only update if element exists and value is not undefined/null
if (element && value !== undefined && value !== null) {
element.textContent = value;
} else if (element) {
element.textContent = '...'; // Show fallback if data missing
}
}
// Update bio if available and element exists
if (data.bio) {
const bioElement = document.querySelector('#home p'); // Target hero paragraph
if (bioElement) bioElement.textContent = data.bio;
}
// Update GitHub stats summary paragraph
const connectSummary = document.querySelector('#connect p.text-center');
if (connectSummary && data.public_repos !== undefined) {
connectSummary.innerHTML = `You can find me on GitHub where I contribute to various projects and maintain my own <strong>${data.public_repos} public repositories</strong>.`;
}
}
// Store initial static values from HTML for fallback
const initialStats = {};
const initialProjects = [];
async function fetchGitHubRepos() {
const cacheKey = 'githubReposData';
const cachedResult = cache.get(cacheKey);
if (cachedResult) {
console.log('Using cached GitHub repo data.');
updateFeaturedProjects(cachedResult.value.repos);
updateGitHubStars(cachedResult.value.totalStars); // Update stars separately
return { status: 'cached', expiry: cachedResult.expiry, data: cachedResult.value };
}
console.log('Fetching fresh GitHub repo data...');
try {
// Fetch all public repos to calculate total stars accurately
let allRepos = [];
let page = 1;
while (true) {
const response = await fetch(`https://api.github.com/users/${githubUsername}/repos?per_page=100&page=${page}`);
if (!response.ok) throw new Error(`GitHub API error: ${response.statusText}`);
const repos = await response.json();
if (repos.length === 0) break;
allRepos = allRepos.concat(repos);
page++;
}
const totalStars = allRepos.reduce((sum, repo) => sum + repo.stargazers_count, 0);
const starsElement = document.querySelector('.stat-number[data-stat="stars"]');
if (starsElement) starsElement.textContent = totalStars;
updateFeaturedProjects(allRepos);
// Cache the combined results
const dataToCache = { repos: allRepos, totalStars: totalStars };
cache.set(cacheKey, dataToCache);
return { status: 'live', data: dataToCache };
} catch (error) {
console.error('Error fetching GitHub repos:', error);
// Fallback: use initial static values if available
updateFeaturedProjects(initialProjects);
updateGitHubStars(initialStats.stars);
return { status: 'failed', data: null };
}
}
function updateGitHubStars(totalStars) {
const starsElement = document.querySelector('.stat-number[data-stat="stars"]');
if (starsElement) {
starsElement.textContent = totalStars !== undefined && totalStars !== null ? totalStars : '...';
}
}
function updateFeaturedProjects(repos) {
if (!repos || repos.length === 0) return;
// Sort by stars first, then recently updated for tie-breaking
const sortedRepos = [...repos].sort((a, b) => {
if (b.stargazers_count !== a.stargazers_count) {
return b.stargazers_count - a.stargazers_count;
}
return new Date(b.updated_at) - new Date(a.updated_at);
});
// Filter out forks unless they have significant stars, and get top 2
const topRepos = sortedRepos.filter(repo => !repo.fork || repo.stargazers_count > 10).slice(0, 2);
const projectsContainer = document.querySelector('#projects .container'); // Target container
if (!projectsContainer) return;
const projectItems = projectsContainer.querySelectorAll('.item');
// Only replace if we found good repos
if (topRepos.length > 0) {
topRepos.forEach((repo, index) => {
if (index < projectItems.length) {
const item = projectItems[index];
const headingLink = item.querySelector('h3 a');
const description = item.querySelector('p'); // First paragraph is description
const meta = item.querySelector('.item-meta'); // Select the meta div
const tagsContainer = item.querySelector('.tags');
if (headingLink) {
headingLink.textContent = repo.name;
headingLink.href = repo.html_url;
}
// Ensure description exists before trying to set textContent
if (description) {
description.textContent = repo.description || 'No description provided.';
}
// Update Item Meta (ensure meta element exists)
// Update Meta (example: repo language or main topic)
if (meta && repo.language) {
meta.innerHTML = `<i class="fas fa-code"></i> ${repo.language}`;
} else if (meta) {
// Clear meta if no language
meta.innerHTML = '';
}
if (tagsContainer) {
tagsContainer.innerHTML = ''; // Clear existing tags
if (repo.language) {
const langTag = document.createElement('span');
langTag.className = 'tag';
langTag.textContent = repo.language;
tagsContainer.appendChild(langTag);
}
// Add stars tag
const starsTag = document.createElement('span');
starsTag.className = 'tag';
starsTag.innerHTML = `<i class="fas fa-star" style="margin-right: 4px;"></i> ${repo.stargazers_count}`;
tagsContainer.appendChild(starsTag);
// Add forks tag
const forksTag = document.createElement('span');
forksTag.className = 'tag';
forksTag.innerHTML = `<i class="fas fa-code-branch" style="margin-right: 4px;"></i> ${repo.forks_count}`;
tagsContainer.appendChild(forksTag);
}
}
});
// If fewer than 2 top repos, hide the remaining placeholder(s)
if (topRepos.length < projectItems.length) {
for (let i = topRepos.length; i < projectItems.length; i++) {
projectItems[i].style.display = 'none';
}
}
} else if (projectItems.length > 0) { // Only add message if placeholders existed
// If no good repos found, maybe hide the default examples or show a message
projectItems.forEach(item => item.style.display = 'none');
const noProjectsMsg = document.createElement('p');
noProjectsMsg.textContent = "Featured projects from GitHub will appear here.";
noProjectsMsg.style.textAlign = 'center';
noProjectsMsg.style.color = 'var(--subtle-text)';
projectsContainer.appendChild(noProjectsMsg);
}
}
async function fetchGitHubActivity() {
const cacheKey = 'githubActivityData';
const cachedResult = cache.get(cacheKey);
if (cachedResult) {
console.log('Using cached GitHub activity data.');
updateActivityFeed(cachedResult.value);
return { status: 'cached', expiry: cachedResult.expiry, data: cachedResult.value };
}
console.log('Fetching fresh GitHub activity data...');
try {
const response = await fetch(`https://api.github.com/users/${githubUsername}/events/public?per_page=15`); // Fetch a bit more initially
if (!response.ok) throw new Error(`GitHub API error: ${response.statusText}`);
const events = await response.json();
updateActivityFeed(events);
cache.set(cacheKey, events);
return { status: 'live', data: events };
} catch (error) {
console.error('Error fetching GitHub activity:', error);
// Fallback: potentially clear the feed or show a message?
updateActivityFeed([]); // Clear feed on error or show cached if available?
return { status: 'failed', data: null };
}
}
function updateActivityFeed(events) {
if (!events || events.length === 0) return;
const connectContainer = document.querySelector('#connect .container'); // Target container
if (!connectContainer) return;
// Find the achievements div to insert after
const achievementsDiv = connectContainer.querySelector('.achievements');
if (!achievementsDiv) return; // Cannot insert if anchor element is missing
// Remove existing feed if present
let existingFeed = connectContainer.querySelector('.activity-feed');
let existingHeading = connectContainer.querySelector('h3.activity-heading');
if (existingFeed) existingFeed.remove();
if (existingHeading) existingHeading.remove();
// Filter for meaningful events
const meaningfulEvents = events.filter(event =>
['PushEvent', 'PullRequestEvent', 'IssuesEvent', 'CreateEvent', 'ReleaseEvent', 'ForkEvent', 'WatchEvent'].includes(event.type)
).slice(0, 5); // Show top 5
// Only create feed if there are events to show
if (meaningfulEvents.length > 0) {
// Create heading for the feed
const heading = document.createElement('h3');
heading.className = 'text-center activity-heading'; // Add class for potential removal
heading.style.marginTop = '3em';
heading.style.marginBottom = '1.5em';
heading.textContent = 'Recent GitHub Activity';
// Create feed container
const activityFeed = document.createElement('div');
activityFeed.className = 'activity-feed';
// Insert heading and feed after achievements
achievementsDiv.parentNode.insertBefore(heading, achievementsDiv.nextSibling);
heading.parentNode.insertBefore(activityFeed, heading.nextSibling);
meaningfulEvents.forEach(event => {
const item = document.createElement('div');
item.className = 'activity-item';
const date = new Date(event.created_at);
const formattedDate = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
let icon = 'fas fa-question-circle'; // Default icon
let actionText = '';
const repoName = event.repo.name;
const repoUrl = `https://github.com/${repoName}`;
let targetUrl = repoUrl; // Default target link
switch (event.type) {
case 'PushEvent':
icon = 'fas fa-arrow-up';
const branch = event.payload.ref.split('/').pop();
const commitCount = event.payload.commits?.length || 0;
// Use main repo URL instead of branch-specific URL to avoid 404s on deleted branches
actionText = `Pushed ${commitCount} commit${commitCount !== 1 ? 's' : ''} to <a href="${repoUrl}" target="_blank">${repoName}</a>`;
break;
case 'PullRequestEvent':
icon = 'fas fa-code-pull-request';
const pr = event.payload.pull_request;
actionText = `${event.payload.action.charAt(0).toUpperCase() + event.payload.action.slice(1)} pull request <a href="${pr.html_url}" target="_blank">#${pr.number}</a> in <a href="${repoUrl}" target="_blank">${repoName}</a>`;
targetUrl = pr.html_url;
break;
case 'IssuesEvent':
icon = 'fas fa-circle-exclamation'; // Updated icon
const issue = event.payload.issue;
actionText = `${event.payload.action.charAt(0).toUpperCase() + event.payload.action.slice(1)} issue <a href="${issue.html_url}" target="_blank">#${issue.number}</a> in <a href="${repoUrl}" target="_blank">${repoName}</a>`;
targetUrl = issue.html_url;
break;
case 'CreateEvent':
icon = 'fas fa-plus';
const refType = event.payload.ref_type;
if (refType === 'repository') {
actionText = `Created repository <a href="${repoUrl}" target="_blank">${repoName}</a>`;
} else if (refType === 'branch' || refType === 'tag') {
actionText = `Created ${refType} <strong>${event.payload.ref}</strong> in <a href="${repoUrl}" target="_blank">${repoName}</a>`;
} else {
actionText = `Created something in <a href="${repoUrl}" target="_blank">${repoName}</a>`;
}
break;
case 'ReleaseEvent':
icon = 'fas fa-tag';
const release = event.payload.release;
actionText = `Published release <a href="${release.html_url}" target="_blank">${release.tag_name}</a> for <a href="${repoUrl}" target="_blank">${repoName}</a>`;
targetUrl = release.html_url;
break;
case 'ForkEvent':
icon = 'fas fa-code-branch'; // Use fork icon
const fork = event.payload.forkee;
actionText = `Forked <a href="${repoUrl}" target="_blank">${repoName}</a> to <a href="${fork.html_url}" target="_blank">${fork.full_name}</a>`;
targetUrl = fork.html_url;
break;
case 'WatchEvent': // User starred a repo
icon = 'fas fa-star';
actionText = `Starred repository <a href="${repoUrl}" target="_blank">${repoName}</a>`;
break;
}
item.innerHTML = ` <div class="activity-icon"><i class="${icon}"></i></div>
<div class="activity-content">
<div class="activity-action">${actionText}</div>
<div class="activity-date">${formattedDate}</div>
</div>
`;
// Optional: make the whole item clickable
item.style.cursor = 'pointer';
item.onclick = () => window.open(targetUrl, '_blank');
activityFeed.appendChild(item);
});
} else {
// Optional: display message if no recent meaningful activity
// console.log("No recent meaningful GitHub activity found to display.");
}
}
// ===== Architecture Diagram Panel Toggle =====
function setupArchDiagrams() {
const toggleBtns = document.querySelectorAll('.arch-toggle-btn');
toggleBtns.forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent card hover effects from interfering
const targetId = btn.getAttribute('data-target');
const panel = document.getElementById(targetId);
if (!panel) return;
const isExpanded = panel.classList.contains('expanded');
// Toggle panel
if (isExpanded) {
panel.classList.remove('expanded');
btn.classList.remove('active');
btn.setAttribute('aria-expanded', 'false');
} else {
panel.classList.add('expanded');
btn.classList.add('active');
btn.setAttribute('aria-expanded', 'true');
// Stagger-animate the nodes appearing
const nodes = panel.querySelectorAll('.arch-node');
nodes.forEach((node, i) => {
node.style.opacity = '0';
node.style.transform = 'translateY(10px)';
setTimeout(() => {
node.style.transition = 'opacity 0.4s ease, transform 0.4s ease';
node.style.opacity = '1';
node.style.transform = 'translateY(0)';
}, 80 + i * 50);
});
// Stagger-animate connectors
const connectors = panel.querySelectorAll('.arch-connector, .arch-h-connector');
connectors.forEach((conn, i) => {
conn.style.opacity = '0';
setTimeout(() => {
conn.style.transition = 'opacity 0.5s ease';
conn.style.opacity = '1';
}, 200 + i * 80);
});
// Scroll the panel into view smoothly after expansion
setTimeout(() => {
panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}, 100);
}
});
});
// Prevent project-card hover transform when panel is expanded
const projectCards = document.querySelectorAll('.project-card');
projectCards.forEach(card => {
const panel = card.querySelector('.arch-panel');
if (panel) {
// Disable the card lift on hover when diagram is open
const observer = new MutationObserver(() => {
if (panel.classList.contains('expanded')) {
card.style.transform = 'none';
} else {
card.style.transform = '';
}
});
observer.observe(panel, { attributes: true, attributeFilter: ['class'] });
}
});
}
// ===== Dynamic Blog Posts Loader =====
function setupBlogPosts() {
const blogGrid = document.getElementById('blogGrid');
if (!blogGrid) return;
const MAX_POSTS = 4; // Show latest 4 on landing page
fetch('/blog/posts.json')
.then(r => {
if (!r.ok) throw new Error('Failed to load posts');
return r.json();
})
.then(posts => {
// Sort by date descending (newest first)
posts.sort((a, b) => new Date(b.date) - new Date(a.date));
// Take only the latest posts for the landing page
const latestPosts = posts.slice(0, MAX_POSTS);
blogGrid.innerHTML = '';
latestPosts.forEach((post, i) => {
const isNew = isWithinDays(post.date, 7);
const card = document.createElement('a');
card.href = post.url;
card.className = 'blog-card';
card.style.opacity = '0';
card.style.transform = 'translateY(20px)';
const seriesTag = post.series
? `<span class="blog-series">${post.series}</span>`
: '';
const statusBadge = isNew
? '<span class="blog-status" style="background: rgba(16, 185, 129, 0.9);">New</span>'
: '';
const dateStr = formatDate(post.date);
card.innerHTML = `
<img src="${post.image}" alt="${post.title}" class="blog-image" loading="lazy">
<div class="blog-content">
<div class="blog-meta">
${statusBadge}
${seriesTag}
<span class="blog-date">${dateStr}</span>
</div>
<h3 class="blog-title">${post.title}</h3>
<p class="blog-description">${post.description}</p>
</div>
`;
blogGrid.appendChild(card);
// Stagger animation
setTimeout(() => {
card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
card.style.opacity = '1';
card.style.transform = 'translateY(0)';
}, 100 + i * 100);
});
})
.catch(err => {
console.warn('Blog posts failed to load:', err);
blogGrid.innerHTML = '<p style="text-align:center; color: var(--text-secondary, #888); grid-column:1/-1;">Blog posts unavailable</p>';
});
}
function isWithinDays(dateStr, days) {
const postDate = new Date(dateStr);
const now = new Date();
const diffMs = now - postDate;
return diffMs >= 0 && diffMs < days * 24 * 60 * 60 * 1000;
}
function formatDate(dateStr) {
const d = new Date(dateStr + 'T00:00:00');
return d.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
}
// Initialize architecture diagrams on DOM ready (or immediately if already loaded)
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
setupArchDiagrams();
setupBlogPosts();
});
} else {
setupArchDiagrams();
setupBlogPosts();
}
})(); // end IIFE