Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
555 lines (503 loc) · 21.6 KB
/
Copy pathscript.js
File metadata and controls
555 lines (503 loc) · 21.6 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
/* =========================================================
Mehedi Hasan Portfolio — interactions & progressive effects
========================================================= */
(() => {
'use strict';
const onReady = (callback) => {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', callback, { once: true });
} else {
callback();
}
};
onReady(() => {
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const finePointer = window.matchMedia('(hover: hover) and (pointer: fine)').matches;
const isSmallScreen = window.matchMedia('(max-width: 760px)').matches;
/* 1. Loading screen: always release it, even if window load is delayed. */
const loadingScreen = document.getElementById('loadingScreen');
let loadingReleased = false;
const releaseLoadingScreen = () => {
if (loadingReleased || !loadingScreen) return;
loadingReleased = true;
loadingScreen.classList.add('hidden');
window.setTimeout(() => loadingScreen.remove(), 650);
};
if (document.readyState === 'complete') {
window.setTimeout(releaseLoadingScreen, reduceMotion ? 0 : 250);
} else {
window.addEventListener('load', () => {
window.setTimeout(releaseLoadingScreen, reduceMotion ? 0 : 450);
}, { once: true });
}
window.setTimeout(releaseLoadingScreen, 2500);
/* 2. Mobile navigation with keyboard and outside-click support. */
const hamburger = document.getElementById('hamburger');
const navLinks = document.getElementById('navLinks');
const header = document.querySelector('.header');
if (hamburger && navLinks) {
const setMenuOpen = (open) => {
navLinks.classList.toggle('open', open);
hamburger.setAttribute('aria-expanded', String(open));
hamburger.setAttribute('aria-label', open ? 'Close navigation' : 'Open navigation');
document.body.classList.toggle('menu-open', open && isSmallScreen);
};
hamburger.addEventListener('click', (event) => {
event.stopPropagation();
setMenuOpen(hamburger.getAttribute('aria-expanded') !== 'true');
});
navLinks.querySelectorAll('a[href^="#"]').forEach((link) => {
link.addEventListener('click', () => setMenuOpen(false));
});
document.addEventListener('click', (event) => {
if (!navLinks.contains(event.target) && !hamburger.contains(event.target)) {
setMenuOpen(false);
}
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
setMenuOpen(false);
hamburger.focus();
}
});
window.addEventListener('resize', () => {
if (window.innerWidth > 760) setMenuOpen(false);
}, { passive: true });
}
/* 3. Smooth in-page navigation; preserve native behavior for external links. */
document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
anchor.addEventListener('click', (event) => {
const href = anchor.getAttribute('href');
if (!href || href === '#') return;
let target;
try { target = document.querySelector(href); } catch (_) { return; }
if (!target) return;
event.preventDefault();
const headerHeight = header ? header.getBoundingClientRect().height : 0;
const targetTop = target.getBoundingClientRect().top + window.scrollY - headerHeight - 12;
window.scrollTo({ top: Math.max(0, targetTop), behavior: reduceMotion ? 'auto' : 'smooth' });
if (window.history && window.history.pushState) {
window.history.pushState(null, '', href);
}
});
});
/* Bidirectional scroll reveal: reset when leaving the viewport, replay on re-entry. */
if (!reduceMotion && 'IntersectionObserver' in window) {
const revealTargets = document.querySelectorAll(
'.about-grid, .about-badge, .stats-item, .experience-item, .service-card, ' +
'.tool-item, .portfolio-card, .testimonial-card, .cta .container > *'
);
let previousScrollY = window.scrollY;
let scrollDirection = 'down';
let directionFrame = 0;
window.addEventListener('scroll', () => {
const currentY = window.scrollY;
if (currentY !== previousScrollY) {
scrollDirection = currentY > previousScrollY ? 'down' : 'up';
previousScrollY = currentY;
}
if (!directionFrame) {
directionFrame = window.requestAnimationFrame(() => { directionFrame = 0; });
}
}, { passive: true });
const revealObserver = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
const element = entry.target;
if (entry.isIntersecting) {
element.style.setProperty('--reveal-offset', scrollDirection === 'down' ? '34px' : '-34px');
element.classList.add('is-visible');
} else {
element.classList.remove('is-visible');
}
});
}, { threshold: 0.12, rootMargin: '0px 0px -5% 0px' });
revealTargets.forEach((element, index) => {
element.classList.add('scroll-reveal');
if (element.matches('.stats-item, .service-card, .tool-item, .portfolio-card, .testimonial-card')) {
element.style.transitionDelay = `${(index % 4) * 75}ms`;
}
revealObserver.observe(element);
});
}
/* Floating back-to-top button: reveal after scrolling down. */
const backToTop = document.getElementById('backToTop');
if (backToTop) {
const updateBackToTop = () => {
backToTop.classList.toggle('is-visible', window.scrollY > 420);
};
updateBackToTop();
window.addEventListener('scroll', updateBackToTop, { passive: true });
backToTop.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: reduceMotion ? 'auto' : 'smooth' });
});
}
/* 4. Footer year and live Bangladesh local time. */
const year = document.getElementById('year');
if (year) year.textContent = String(new Date().getFullYear());
const localTime = document.getElementById('localTime');
if (localTime) {
const updateLocalTime = () => {
const time = new Intl.DateTimeFormat('en-US', {
timeZone: 'Asia/Dhaka',
hour: 'numeric',
minute: '2-digit',
hour12: true
}).format(new Date());
localTime.textContent = `Local Time · ${time}`;
};
updateLocalTime();
window.setInterval(updateLocalTime, 15000);
}
/* 5. Count-up stats only when visible. Keep any suffix such as + or %. */
const counters = document.querySelectorAll('.stats-item .value');
const animateCounter = (element) => {
if (element.dataset.counted === 'true') return;
element.dataset.counted = 'true';
const original = element.textContent.trim();
const match = original.match(/^([\d,]+)(.*)$/);
if (!match) return;
const target = Number(match[1].replace(/,/g, ''));
const suffix = match[2];
if (!Number.isFinite(target)) return;
if (reduceMotion) {
element.textContent = `${target.toLocaleString()}${suffix}`;
return;
}
const duration = 1200;
const start = performance.now();
const step = (now) => {
const progress = Math.min((now - start) / duration, 1);
const eased = 1 - Math.pow(1 - progress, 3);
element.textContent = `${Math.round(target * eased).toLocaleString()}${suffix}`;
if (progress < 1) window.requestAnimationFrame(step);
};
window.requestAnimationFrame(step);
};
if ('IntersectionObserver' in window && counters.length) {
const counterObserver = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
animateCounter(entry.target);
observer.unobserve(entry.target);
}
});
}, { threshold: 0.35 });
counters.forEach((counter) => counterObserver.observe(counter));
} else {
counters.forEach(animateCounter);
}
/* 6. Neural background: pause off-screen and when tab is hidden. */
const canvas = document.getElementById('neuralCanvas');
if (canvas && !reduceMotion && !isSmallScreen && finePointer) {
const context = canvas.getContext('2d', { alpha: true });
if (context) {
let width = 0;
let height = 0;
let nodes = [];
let frameId = 0;
let running = false;
const pointer = { x: -10000, y: -10000, radius: 190, active: false };
const maxDpr = 1.5;
const resizeCanvas = () => {
const dpr = Math.min(window.devicePixelRatio || 1, maxDpr);
width = window.innerWidth;
height = window.innerHeight;
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
context.setTransform(dpr, 0, 0, dpr, 0, 0);
const count = Math.min(92, Math.max(38, Math.floor((width * height) / 18500)));
nodes = Array.from({ length: count }, () => ({
x: Math.random() * width,
y: Math.random() * height,
vx: (Math.random() - 0.5) * 0.28,
vy: (Math.random() - 0.5) * 0.28,
radius: Math.random() * 1.55 + 0.9,
hue: Math.random() > 0.5 ? 186 : 255
}));
};
const draw = () => {
if (!running || document.hidden) return;
context.clearRect(0, 0, width, height);
for (let i = 0; i < nodes.length; i += 1) {
const node = nodes[i];
// Gentle magnetic attraction: accelerate nearby nodes toward the pointer.
const dx = pointer.x - node.x;
const dy = pointer.y - node.y;
const mouseDistance = pointer.active ? Math.hypot(dx, dy) : pointer.radius + 1;
const influence = Math.max(0, 1 - mouseDistance / pointer.radius);
if (influence > 0) {
node.vx += dx * influence * 0.0018;
node.vy += dy * influence * 0.0018;
}
// Keep motion smooth and bounded so the effect stays lightweight.
node.vx *= 0.997;
node.vy *= 0.997;
const speed = Math.hypot(node.vx, node.vy);
if (speed > 0.85) {
node.vx = (node.vx / speed) * 0.85;
node.vy = (node.vy / speed) * 0.85;
}
node.x += node.vx;
node.y += node.vy;
if (node.x < 0 || node.x > width) node.vx *= -1;
if (node.y < 0 || node.y > height) node.vy *= -1;
const nearPointer = influence > 0;
context.beginPath();
context.arc(node.x, node.y, node.radius + influence * 1.25, 0, Math.PI * 2);
context.fillStyle = `hsla(${node.hue}, 100%, 68%, ${0.68 + influence * 0.3})`;
context.fill();
for (let j = i + 1; j < nodes.length; j += 1) {
const other = nodes[j];
const distance = Math.hypot(node.x - other.x, node.y - other.y);
if (distance < 148) {
const otherInfluence = pointer.active
? Math.max(0, 1 - Math.hypot(pointer.x - other.x, pointer.y - other.y) / pointer.radius)
: 0;
const glow = Math.max(influence, otherInfluence);
const alpha = (1 - distance / 148) * (0.42 + glow * 0.42);
context.beginPath();
context.moveTo(node.x, node.y);
context.lineTo(other.x, other.y);
context.strokeStyle = `rgba(0, 220, 240, ${alpha})`;
context.lineWidth = 0.85 + glow * 0.55;
context.stroke();
}
}
}
frameId = window.requestAnimationFrame(draw);
};
const startAnimation = () => {
if (running || document.hidden) return;
running = true;
frameId = window.requestAnimationFrame(draw);
};
const stopAnimation = () => {
running = false;
if (frameId) window.cancelAnimationFrame(frameId);
frameId = 0;
};
resizeCanvas();
startAnimation();
window.addEventListener('resize', resizeCanvas, { passive: true });
window.addEventListener('mousemove', (event) => {
pointer.x = event.clientX;
pointer.y = event.clientY;
pointer.active = true;
}, { passive: true });
window.addEventListener('mouseout', (event) => {
if (!event.relatedTarget) {
pointer.x = -10000;
pointer.y = -10000;
pointer.active = false;
}
});
document.addEventListener('visibilitychange', () => {
if (document.hidden) stopAnimation();
else startAnimation();
});
}
}
/* 7. Custom cursor and spotlight: desktop only, guarded against missing nodes. */
if (finePointer && !reduceMotion) {
const cursor = document.getElementById('customCursor');
const cursorDot = document.getElementById('customCursorDot');
const spotlight = document.getElementById('mouseSpotlight');
if (cursor && cursorDot && spotlight) {
let targetX = window.innerWidth / 2;
let targetY = window.innerHeight / 2;
let currentX = targetX;
let currentY = targetY;
let cursorFrame = 0;
const movePointer = (event) => {
targetX = event.clientX;
targetY = event.clientY;
cursorDot.style.transform = `translate3d(${targetX}px, ${targetY}px, 0) translate(-50%, -50%)`;
spotlight.style.transform = `translate3d(${targetX}px, ${targetY}px, 0) translate(-50%, -50%)`;
};
const animateCursor = () => {
currentX += (targetX - currentX) * 0.22;
currentY += (targetY - currentY) * 0.22;
cursor.style.transform = `translate3d(${currentX}px, ${currentY}px, 0) translate(-50%, -50%)`;
cursorFrame = window.requestAnimationFrame(animateCursor);
};
window.addEventListener('mousemove', movePointer, { passive: true });
animateCursor();
document.querySelectorAll('a, button, .service-card, .portfolio-card, .testimonial-card, .tool-item')
.forEach((item) => {
item.addEventListener('pointerenter', () => cursor.classList.add('hover'));
item.addEventListener('pointerleave', () => cursor.classList.remove('hover'));
});
window.addEventListener('pointerdown', () => cursor.classList.add('click'));
window.addEventListener('pointerup', () => cursor.classList.remove('click'));
document.addEventListener('visibilitychange', () => {
if (document.hidden && cursorFrame) window.cancelAnimationFrame(cursorFrame);
else if (!document.hidden) animateCursor();
});
document.addEventListener('mouseout', (event) => {
if (!event.relatedTarget) {
cursor.style.opacity = '0';
cursorDot.style.opacity = '0';
spotlight.style.opacity = '0';
}
});
document.addEventListener('mouseover', () => {
cursor.style.opacity = '1';
cursorDot.style.opacity = '1';
spotlight.style.opacity = '';
});
}
}
});
})();
/* 8. Progressive Web App: install prompt, platform guidance, and offline shell. */
(() => {
'use strict';
const button = document.getElementById('installAppButton');
const toast = document.getElementById('installToast');
if (!button || !toast) return;
let deferredPrompt = null;
let toastTimer = 0;
const isStandalone = () => window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true;
const showToast = (message) => {
toast.textContent = message;
toast.hidden = false;
toast.classList.add('is-visible');
window.clearTimeout(toastTimer);
toastTimer = window.setTimeout(() => {
toast.classList.remove('is-visible');
window.setTimeout(() => { toast.hidden = true; }, 250);
}, 6500);
};
const markInstalled = () => {
button.querySelector('span').textContent = 'App Installed';
button.disabled = true;
button.classList.add('is-installed');
};
if (isStandalone()) markInstalled();
window.addEventListener('beforeinstallprompt', (event) => {
event.preventDefault();
deferredPrompt = event;
});
button.addEventListener('click', async () => {
if (isStandalone()) {
showToast('Mehedi Portfolio is already installed on this device.');
markInstalled();
return;
}
if (deferredPrompt) {
deferredPrompt.prompt();
const choice = await deferredPrompt.userChoice;
if (choice && choice.outcome === 'accepted') {
showToast('Thanks! Mehedi Portfolio is being installed.');
} else {
showToast('Installation was cancelled. You can install it anytime from here.');
}
deferredPrompt = null;
return;
}
const ua = navigator.userAgent || '';
const isIOS = /iphone|ipad|ipod/i.test(ua);
const isMac = /Macintosh/i.test(ua) && navigator.maxTouchPoints > 1;
if (isIOS || isMac) {
showToast('To install: tap Share, then choose “Add to Home Screen”.');
} else if (/android/i.test(ua)) {
showToast('Open your browser menu (⋮), then choose “Install app” or “Add to Home screen”.');
} else {
showToast('In Chrome or Edge, open the browser menu and choose “Install page as app” or “Install Mehedi Portfolio”.');
}
});
window.addEventListener('appinstalled', () => {
markInstalled();
showToast('Mehedi Portfolio has been installed successfully.');
deferredPrompt = null;
});
if ('serviceWorker' in navigator && (location.protocol === 'https:' || location.hostname === 'localhost' || location.hostname === '127.0.0.1')) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('./service-worker.js').catch((error) => {
console.warn('Service worker registration failed:', error);
});
}, { once: true });
}
})();
/* Project Showcase: accessible image and description lightbox. */
(() => {
'use strict';
const initProjectLightbox = () => {
const cards = [...document.querySelectorAll('.portfolio-card')];
if (!cards.length) return;
const overlay = document.createElement('div');
overlay.className = 'project-lightbox';
overlay.setAttribute('aria-hidden', 'true');
overlay.innerHTML = `
<div class="project-lightbox__panel" role="dialog" aria-modal="true" aria-labelledby="projectLightboxTitle" aria-describedby="projectLightboxDescription" tabindex="-1">
<button class="project-lightbox__close" type="button" aria-label="Close project preview">×</button>
<div class="project-lightbox__image-wrap"><img class="project-lightbox__image" alt=""></div>
<div class="project-lightbox__caption">
<h2 id="projectLightboxTitle"></h2>
<p id="projectLightboxDescription"></p>
</div>
</div>`;
document.body.appendChild(overlay);
const panel = overlay.querySelector('.project-lightbox__panel');
const previewImage = overlay.querySelector('.project-lightbox__image');
const title = overlay.querySelector('#projectLightboxTitle');
const description = overlay.querySelector('#projectLightboxDescription');
const closeButton = overlay.querySelector('.project-lightbox__close');
let previousFocus = null;
const close = () => {
if (!overlay.classList.contains('is-open')) return;
overlay.classList.remove('is-open');
overlay.setAttribute('aria-hidden', 'true');
document.body.classList.remove('lightbox-open');
if (previousFocus && previousFocus.isConnected) previousFocus.focus();
};
const open = (card, trigger) => {
const image = card.querySelector('.thumb img');
const heading = card.querySelector('.body h3');
const copy = card.querySelector('.body p');
if (!image || !heading || !copy) return;
previousFocus = trigger;
previewImage.src = image.currentSrc || image.src;
previewImage.alt = image.alt || heading.textContent.trim();
title.textContent = heading.textContent.trim();
description.textContent = copy.textContent.trim();
overlay.classList.add('is-open');
overlay.setAttribute('aria-hidden', 'false');
document.body.classList.add('lightbox-open');
closeButton.focus();
};
cards.forEach((card) => {
const image = card.querySelector('.thumb img');
if (!image) return;
image.tabIndex = 0;
image.setAttribute('role', 'button');
image.setAttribute('aria-haspopup', 'dialog');
image.setAttribute('aria-label', `View ${image.alt || 'project'} image and details`);
image.addEventListener('click', () => open(card, image));
image.addEventListener('keydown', (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
open(card, image);
}
});
});
closeButton.addEventListener('click', close);
overlay.addEventListener('click', (event) => { if (event.target === overlay) close(); });
panel.addEventListener('click', (event) => event.stopPropagation());
document.addEventListener('keydown', (event) => {
if (!overlay.classList.contains('is-open')) return;
if (event.key === 'Escape') close();
if (event.key === 'Tab') {
event.preventDefault();
closeButton.focus();
}
});
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initProjectLightbox, { once: true });
} else {
initProjectLightbox();
}
})();