-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
401 lines (356 loc) · 16.1 KB
/
script.js
File metadata and controls
401 lines (356 loc) · 16.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
document.addEventListener('DOMContentLoaded', () => {
const nav = document.querySelector('nav[role="navigation"]');
const toggle = document.getElementById('nav-toggle');
if (!nav || !toggle) return;
function setOpen(isOpen) {
nav.classList.toggle('is-open', isOpen);
nav.setAttribute('data-open', isOpen ? 'true' : 'false');
toggle.setAttribute('aria-expanded', String(isOpen));
}
toggle.addEventListener('click', () => {
const isOpen = !nav.classList.contains('is-open');
setOpen(isOpen);
if (isOpen) {
// move focus into nav for keyboard users
const firstLink = nav.querySelector('a');
if (firstLink) firstLink.focus();
}
});
// Close on Escape
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && nav.classList.contains('is-open')) {
setOpen(false);
toggle.focus();
}
});
// Close when clicking outside
document.addEventListener('click', (e) => {
if (!nav.contains(e.target) && !toggle.contains(e.target) && nav.classList.contains('is-open')) {
setOpen(false);
}
});
// Smooth scrolling for same-page links: JS fallback + accessible focus management
function isSmoothScrollSupported() {
try {
return 'scrollBehavior' in document.documentElement.style || (window.CSS && CSS.supports && CSS.supports('scroll-behavior', 'smooth'));
} catch (e) {
return false;
}
}
function animateScrollTo(targetY, duration = 500) {
const startY = window.pageYOffset;
const diff = targetY - startY;
if (!diff) return Promise.resolve();
let start;
return new Promise((resolve) => {
function step(ts) {
start = start || ts;
const elapsed = Math.min((ts - start) / duration, 1);
// easeInOutQuad
const eased = elapsed < 0.5 ? 2 * elapsed * elapsed : -1 + (4 - 2 * elapsed) * elapsed;
window.scrollTo(0, Math.round(startY + diff * eased));
if (elapsed < 1) requestAnimationFrame(step);
else resolve();
}
requestAnimationFrame(step);
});
}
function focusElement(el) {
if (!el) return;
const tag = el.tagName;
const focusable = el.hasAttribute('tabindex') || /^(A|BUTTON|INPUT|TEXTAREA|SELECT)$/.test(tag) || el.getAttribute('contenteditable') === 'true';
if (!focusable) {
el.setAttribute('tabindex', '-1');
el.dataset._tempTabindex = 'true';
}
el.focus({ preventScroll: true });
if (el.dataset._tempTabindex) {
setTimeout(() => {
el.removeAttribute('tabindex');
delete el.dataset._tempTabindex;
}, 1000);
}
}
document.addEventListener('click', (e) => {
const anchor = e.target.closest('a[href^="#"]');
if (!anchor) return;
const href = anchor.getAttribute('href');
if (!href || href === '#' || href === '#!') return;
const id = href.slice(1);
const target = document.getElementById(id);
if (!target) return;
// Only intercept same-page links
if (location.pathname === anchor.pathname && location.hostname === anchor.hostname) {
e.preventDefault();
const header = document.querySelector('header');
const headerFixed = header && window.getComputedStyle(header).position === 'fixed';
const offset = headerFixed ? header.offsetHeight : 0;
const targetY = Math.max(0, target.getBoundingClientRect().top + window.pageYOffset - offset - 8);
const doScroll = isSmoothScrollSupported()
? (window.scrollTo({ top: targetY, behavior: 'smooth' }), Promise.resolve())
: animateScrollTo(targetY, 500);
doScroll.then(() => {
history.pushState(null, '', `#${id}`);
focusElement(target);
});
}
});
// Projects filter: accessible buttons that show/hide projects, update ARIA and hash
(function initProjectFilter() {
const filterButtons = Array.from(document.querySelectorAll('.filter-btn'));
const projects = Array.from(document.querySelectorAll('.projects-list article'));
const announcer = document.querySelector('.filter-announcer');
if (!filterButtons.length || !projects.length) return;
function applyFilter(filter) {
let visibleCount = 0;
projects.forEach((proj) => {
const tags = (proj.dataset.tags || '').split(',').map(t => t.trim()).filter(Boolean);
const matches = filter === 'all' || tags.includes(filter);
const li = proj.closest('li');
if (li) {
if (matches) {
li.removeAttribute('hidden');
proj.setAttribute('aria-hidden', 'false');
visibleCount++;
} else {
li.setAttribute('hidden', '');
proj.setAttribute('aria-hidden', 'true');
}
}
});
// update buttons' pressed state
filterButtons.forEach((btn) => {
btn.setAttribute('aria-pressed', btn.dataset.filter === filter ? 'true' : 'false');
});
// announce results for screen readers
if (announcer) {
const label = filter === 'all' ? 'all projects' : `${filter} projects`;
announcer.textContent = `Showing ${visibleCount} ${label}`;
}
// update URL hash for deep linking
try {
const newHash = filter === 'all' ? '#projects' : `#projects?filter=${encodeURIComponent(filter)}`;
history.replaceState(null, '', newHash);
} catch (e) { /* ignore */ }
}
// wire up buttons
filterButtons.forEach((btn) => {
btn.addEventListener('click', () => {
applyFilter(btn.dataset.filter || 'all');
});
});
// apply filter from hash if present
(function applyFilterFromHash() {
const hash = location.hash || '';
const m = hash.match(/filter=([^&]+)/);
const filterFromHash = m ? decodeURIComponent(m[1]) : 'all';
const valid = filterButtons.some(b => b.dataset.filter === filterFromHash);
applyFilter(valid ? filterFromHash : 'all');
})();
})();
// Lightbox for project images
(function initLightbox() {
const thumbs = Array.from(document.querySelectorAll('.project-thumb'));
const lightbox = document.getElementById('lightbox');
if (!lightbox || !thumbs.length) return;
const imgEl = lightbox.querySelector('.lightbox__img');
const captionEl = lightbox.querySelector('.lightbox__caption');
const closeBtn = lightbox.querySelector('.lightbox__close');
const prevBtn = lightbox.querySelector('.lightbox__prev');
const nextBtn = lightbox.querySelector('.lightbox__next');
const overlay = lightbox.querySelector('.lightbox__overlay');
// Fallback: if the lightbox image fails to load, show a placeholder
imgEl.addEventListener('error', () => {
imgEl.src = 'images/placeholder.svg';
imgEl.alt = 'Image not available';
});
let currentIndex = -1;
let lastFocused = null;
function show(index) {
const thumb = thumbs[index];
if (!thumb) return;
const full = thumb.dataset.full || thumb.src;
const caption = thumb.closest('figure')?.querySelector('figcaption')?.textContent || thumb.alt || '';
imgEl.src = full;
imgEl.alt = thumb.alt || '';
captionEl.textContent = caption;
currentIndex = index;
lightbox.hidden = false;
lightbox.setAttribute('aria-hidden', 'false');
lastFocused = document.activeElement;
closeBtn.focus();
preload(index - 1);
preload(index + 1);
}
function preload(i) {
const t = thumbs[i];
if (!t) return;
const src = t.dataset.full || t.src;
const im = new Image();
im.src = src;
}
function close() {
lightbox.hidden = true;
lightbox.setAttribute('aria-hidden', 'true');
imgEl.src = '';
captionEl.textContent = '';
if (lastFocused && lastFocused.focus) lastFocused.focus();
currentIndex = -1;
}
function next() {
if (currentIndex < thumbs.length - 1) show(currentIndex + 1);
else show(0);
}
function prev() {
if (currentIndex > 0) show(currentIndex - 1);
else show(thumbs.length - 1);
}
thumbs.forEach((thumb, i) => {
thumb.setAttribute('tabindex', '0');
// If a thumbnail fails to load, replace it with the placeholder to avoid broken icons
thumb.addEventListener('error', () => {
if (!thumb.dataset._errored) {
thumb.dataset._errored = 'true';
thumb.src = 'images/placeholder.svg';
if (!thumb.dataset.full) thumb.dataset.full = 'images/placeholder.svg';
}
});
thumb.addEventListener('click', (e) => {
e.preventDefault();
show(i);
});
thumb.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
show(i);
}
});
});
closeBtn.addEventListener('click', close);
overlay.addEventListener('click', close);
nextBtn.addEventListener('click', next);
prevBtn.addEventListener('click', prev);
document.addEventListener('keydown', (e) => {
if (lightbox.hidden || lightbox.getAttribute('aria-hidden') === 'true') return;
if (e.key === 'Escape') {
e.preventDefault();
close();
} else if (e.key === 'ArrowRight') {
e.preventDefault();
next();
} else if (e.key === 'ArrowLeft') {
e.preventDefault();
prev();
} else if (e.key === 'Tab') {
const focusables = [closeBtn, prevBtn, nextBtn].filter(Boolean);
if (!focusables.length) return;
const idx = focusables.indexOf(document.activeElement);
if (e.shiftKey) {
const nextIdx = idx <= 0 ? focusables.length - 1 : idx - 1;
focusables[nextIdx].focus();
e.preventDefault();
} else {
const nextIdx = idx === -1 || idx === focusables.length - 1 ? 0 : idx + 1;
focusables[nextIdx].focus();
e.preventDefault();
}
}
});
})();
// Contact form: client-side validation, accessible messages, local fallback
(function initContactForm() {
const form = document.getElementById('contact-form');
if (!form) return;
const statusLive = document.getElementById('contact-status');
const messageEl = document.getElementById('form-message');
const submitBtn = form.querySelector('button[type="submit"]');
function setFieldError(el, msg) {
const err = document.getElementById(`${el.id}-error`);
if (err) err.textContent = msg || '';
if (msg) el.setAttribute('aria-invalid', 'true');
else el.removeAttribute('aria-invalid');
}
function clearErrors() {
Array.from(form.elements).forEach((el) => {
if (el.id && el.willValidate) setFieldError(el, '');
});
messageEl.hidden = true;
messageEl.className = 'form-message';
statusLive.textContent = '';
}
// optional: restore draft if present
try {
const draft = localStorage.getItem('contact-draft');
if (draft) {
const data = JSON.parse(draft);
if (data.name) form.querySelector('#name').value = data.name;
if (data.email) form.querySelector('#email').value = data.email;
if (data.message) form.querySelector('#message').value = data.message;
}
} catch (e) { /* ignore */ }
form.addEventListener('submit', (e) => {
e.preventDefault();
clearErrors();
// Built-in constraint validation
if (!form.checkValidity()) {
// show messages for invalid fields
const invalid = Array.from(form.elements).find(el => el.willValidate && !el.checkValidity());
Array.from(form.elements).forEach((el) => {
if (el.willValidate && !el.checkValidity()) {
setFieldError(el, el.validationMessage);
}
});
if (invalid && invalid.focus) invalid.focus();
statusLive.textContent = 'Please fix the highlighted fields.';
return;
}
// prepare submit
submitBtn.disabled = true;
submitBtn.setAttribute('aria-busy', 'true');
statusLive.textContent = 'Sending message…';
const action = (form.getAttribute('action') || '').trim();
const method = (form.getAttribute('method') || 'POST').toUpperCase();
const data = new FormData(form);
// If a real endpoint is provided (not '#' or empty), attempt to POST; otherwise save locally
const shouldSend = action && action !== '#';
if (shouldSend) {
fetch(action, { method, body: data, credentials: 'same-origin' })
.then((res) => {
if (!res.ok) throw new Error('Network error');
return res.json().catch(() => ({}));
})
.then(() => {
messageEl.hidden = false;
messageEl.className = 'form-message success';
messageEl.textContent = 'Thanks — your message was sent.';
statusLive.textContent = 'Message sent.';
form.reset();
localStorage.removeItem('contact-draft');
})
.catch(() => {
messageEl.hidden = false;
messageEl.className = 'form-message error';
messageEl.textContent = 'Sorry — there was a problem sending your message. Your message was saved locally.';
statusLive.textContent = 'Message not sent — saved locally.';
try { localStorage.setItem('contact-draft', JSON.stringify(Object.fromEntries(data))); } catch (err) { /* ignore */ }
})
.finally(() => {
submitBtn.disabled = false;
submitBtn.removeAttribute('aria-busy');
});
} else {
// no backend configured: save locally and simulate quick success
try { localStorage.setItem('contact-draft', JSON.stringify(Object.fromEntries(data))); } catch (err) { /* ignore */ }
setTimeout(() => {
messageEl.hidden = false;
messageEl.className = 'form-message success';
messageEl.textContent = 'Thanks — your message has been saved locally (no server configured).';
statusLive.textContent = 'Message saved locally.';
form.reset();
submitBtn.disabled = false;
submitBtn.removeAttribute('aria-busy');
}, 600);
}
});
})();
});