Repository navigation
Expand file tree
/
Copy pathlab.js
More file actions
491 lines (429 loc) · 17 KB
/
Copy pathlab.js
File metadata and controls
491 lines (429 loc) · 17 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
// Page loader: shown once per session (decided in the page head). The mark is
// written by a pen (CSS); once the page and fonts are ready, and at least
// long enough for the pull to land, the printed logo glides into the header
// logo's exact place and hands over to it.
function runLoader() {
const root = document.documentElement;
if (!root.classList.contains("is-loading")) return;
const start = performance.now();
const shortest = 2650; // the ink settles at ~2.45s, then a short beat
const longest = 3400;
const pageLoaded = new Promise((resolve) => {
if (document.readyState === "complete") resolve();
else addEventListener("load", resolve, { once: true });
});
const ready = Promise.all([pageLoaded, document.fonts ? document.fonts.ready : null]);
const cap = new Promise((resolve) => setTimeout(resolve, longest));
function finish() {
root.classList.add("loader-done");
root.classList.remove("is-loading", "is-loaded");
}
function handOff() {
const mark = document.querySelector(".loader-mark");
const target = document.querySelector(".site-header .logo");
root.classList.add("is-loaded");
if (!mark || !target) return setTimeout(finish, 700);
const from = mark.getBoundingClientRect();
const to = target.getBoundingClientRect();
const inView = to.bottom > 0 && to.top < innerHeight;
if (!inView) {
// header is off-screen (arrived at a section link): just let the sheet fade
mark.style.transition = "opacity 0.4s ease";
mark.style.opacity = "0";
return setTimeout(finish, 700);
}
const scale = to.width / from.width;
mark.style.transition = "transform 0.72s cubic-bezier(0.7, 0, 0.2, 1)";
mark.style.transform =
`translate(${to.left - from.left}px, ${to.top - from.top}px) scale(${scale})`;
mark.addEventListener("transitionend", finish, { once: true });
setTimeout(finish, 1000); // in case transitionend never fires
}
Promise.race([ready, cap]).then(() => {
const wait = Math.max(0, shortest - (performance.now() - start));
setTimeout(handOff, wait);
});
}
runLoader();
// Theme toggle: dark by default; light when the visitor picks it, remembered
// in this browser. The label comes from CSS, so this only switches the theme
// and keeps the button's accessible name right.
(() => {
const button = document.querySelector(".theme-toggle");
if (!button) return;
const root = document.documentElement;
const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)");
const current = () => (root.dataset.theme === "light" ? "light" : "dark");
function render() {
const next = current() === "dark" ? "light" : "dark";
button.setAttribute("aria-label", `Switch to ${next} mode`);
}
function apply(theme) {
if (theme === "light") root.dataset.theme = "light";
else delete root.dataset.theme;
try { localStorage.setItem("theme", theme); } catch (e) {}
render();
}
button.addEventListener("click", () => {
const next = current() === "dark" ? "light" : "dark";
// crossfade the whole page at once where supported, so nothing changes early
if (document.startViewTransition && !reduceMotion.matches) {
document.startViewTransition(() => apply(next));
} else {
apply(next);
}
});
render();
})();
// Project preview plate: on wide screens with a mouse, hovering (or tabbing to)
// a project shows a larger plate in the right margin. It rides a vertical rail,
// following the cursor up and down, leans while it moves and settles straight
// on whole pixels so the image stays sharp when it's still.
(() => {
const list = document.querySelector(".projects");
const column = document.querySelector(".page");
if (!list || !column) return;
const canHover = matchMedia("(hover: hover) and (pointer: fine)");
const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)");
const projects = [...list.querySelectorAll(".project")];
const figure = document.createElement("figure");
figure.className = "preview";
figure.setAttribute("aria-hidden", "true");
figure.innerHTML =
'<div class="preview-plate"><div class="preview-media"></div>' +
'<figcaption><b class="preview-no"></b><span class="preview-name"></span>' +
'<span class="preview-year"></span></figcaption></div>';
document.body.append(figure);
const media = figure.querySelector(".preview-media");
const number = figure.querySelector(".preview-no");
const name = figure.querySelector(".preview-name");
const year = figure.querySelector(".preview-year");
let active = null;
let y = 0;
let targetY = 0;
let tilt = 0;
let frame = 0;
let preloaded = false;
const gap = 40;
const edge = 24;
// width of the free margin to the right of the text column, or 0 if too narrow
function railWidth() {
const right = column.getBoundingClientRect().right - parseFloat(getComputedStyle(column).paddingRight);
const room = innerWidth - right - gap - edge;
return room >= 220 ? Math.min(300, room) : 0;
}
function placeRail() {
const width = railWidth();
if (!width) return false;
const right = column.getBoundingClientRect().right - parseFloat(getComputedStyle(column).paddingRight);
figure.style.width = width + "px";
figure.style.left = right + gap + "px";
return true;
}
function clampY(centre) {
const h = figure.offsetHeight || 220;
return Math.max(edge, Math.min(innerHeight - h - edge, centre - h / 2));
}
function preload() {
if (preloaded) return;
preloaded = true;
projects.forEach((p) => {
const img = new Image();
img.src = p.querySelector("img").currentSrc || p.querySelector("img").src;
});
}
function swapImage(src) {
const img = document.createElement("img");
img.alt = "";
img.src = src;
if (media.children.length && !reduceMotion.matches) img.className = "is-new";
media.append(img);
// keep only the plate underneath and the new one
while (media.children.length > 2) media.firstElementChild.remove();
img.addEventListener("animationend", () => {
while (media.firstElementChild !== img) media.firstElementChild.remove();
}, { once: true });
}
function show(project, centreY) {
if (!canHover.matches || !placeRail()) return hide();
if (project === active) return;
const index = projects.indexOf(project);
const wasHidden = !active;
active = project;
swapImage(project.querySelector("img").currentSrc || project.querySelector("img").src);
number.textContent = "fig. " + String(index + 1).padStart(2, "0");
name.textContent = project.querySelector("h3").textContent;
year.textContent = project.dataset.year || "";
targetY = clampY(centreY);
if (wasHidden) {
y = targetY;
tilt = 0;
}
figure.classList.add("is-on");
tick();
}
function hide() {
active = null;
figure.classList.remove("is-on");
}
function tick() {
cancelAnimationFrame(frame);
figure.style.willChange = "transform";
const step = () => {
const ease = reduceMotion.matches ? 1 : 0.16;
y += (targetY - y) * ease;
// a little drag: the plate leans into the direction it's moving
const lean = reduceMotion.matches ? 0 : Math.max(-2.5, Math.min(2.5, (targetY - y) * 0.035));
tilt += (lean - tilt) * (reduceMotion.matches ? 1 : 0.2);
const moving = Math.abs(targetY - y) > 0.5 || Math.abs(tilt) > 0.02;
if (moving) {
figure.style.transform = `translate3d(0, ${y.toFixed(2)}px, 0) rotate(${tilt.toFixed(3)}deg)`;
frame = requestAnimationFrame(step);
} else {
// at rest: no rotation, whole pixels, no compositing layer, so it renders crisp
y = Math.round(targetY);
tilt = 0;
figure.style.transform = `translateY(${y}px)`;
figure.style.willChange = "auto";
}
};
step();
}
list.addEventListener("pointerenter", preload);
projects.forEach((project) => {
project.addEventListener("pointerenter", (e) => show(project, e.clientY));
project.addEventListener("focusin", () => {
const r = project.getBoundingClientRect();
show(project, r.top + r.height / 2);
});
});
list.addEventListener("pointermove", (e) => {
if (!active) return;
targetY = clampY(e.clientY);
tick();
});
list.addEventListener("pointerleave", hide);
list.addEventListener("focusout", (e) => {
if (!list.contains(e.relatedTarget)) hide();
});
addEventListener("keydown", (e) => e.key === "Escape" && active && hide());
addEventListener("scroll", () => active && !list.matches(":hover") && hide(), { passive: true });
addEventListener("resize", () => active && (placeRail() || hide()));
})();
// Scroll motion: M2 hero, M3 header and nav marker, M4/M5 row reveals,
// M8 footer signature.
// One passive scroll listener and one rAF per frame; reveals use an
// IntersectionObserver. Reveals only run when the page has the .motion flag
// (set in the head when reduced motion is off).
(() => {
const root = document.documentElement;
const header = document.querySelector(".site-header");
const nav = document.querySelector(".site-nav");
const hero = document.querySelector(".kinetic");
const sections = ["projects", "playground", "learning", "contact"]
.map((id) => document.getElementById(id))
.filter(Boolean);
if (!header) return;
const motion = root.classList.contains("motion");
// M3: the marker that sits under the current section's link
const marker = document.createElement("span");
marker.className = "nav-marker";
marker.setAttribute("aria-hidden", "true");
nav.append(marker);
const links = new Map(
[...nav.querySelectorAll('a[href^="#"]')].map((a) => [a.getAttribute("href").slice(1), a])
);
let current = null;
function setCurrent(id) {
if (id === current) return;
current = id;
links.forEach((a, key) => a.setAttribute("aria-current", String(key === id)));
const a = id && links.get(id);
if (!a) {
marker.style.opacity = "0";
return;
}
marker.style.opacity = "1";
marker.style.width = a.offsetWidth + "px";
marker.style.transform = `translateX(${a.offsetLeft}px)`;
}
let picked = null;
links.forEach((a, key) => a.addEventListener("click", () => {
// remember the pick once the jump has landed
setTimeout(() => {
picked = { id: key, y: scrollY };
update();
}, 700);
picked = { id: key, y: null }; // held while the page scrolls there
setCurrent(key);
}));
let ticking = false;
function update() {
ticking = false;
const y = scrollY;
header.classList.toggle("is-condensed", y > 120);
// the last section whose top has passed 40% of the screen; at the very
// bottom of the page the last section is current, even if it's short
const max = document.documentElement.scrollHeight - innerHeight;
const line = innerHeight * 0.4;
let id = null;
for (const s of sections) if (s.getBoundingClientRect().top <= line) id = s.id;
if (max > 0 && y >= max - 2) id = sections[sections.length - 1].id;
// a section picked from the nav stays current until you scroll on, even
// when the page is too short to bring it to the top
if (picked && (picked.y === null || Math.abs(y - picked.y) < 40)) id = picked.id;
else picked = null;
setCurrent(id);
// M2: 0 at the top, 1 once the hero has scrolled up under the header
if (hero && motion) {
const box = hero.closest(".hero").getBoundingClientRect();
const span = box.height + box.top + y - 80;
const p = Math.min(1, Math.max(0, y / Math.max(1, span)));
hero.style.setProperty("--hero", p.toFixed(3));
}
}
addEventListener("scroll", () => {
if (!ticking) {
ticking = true;
requestAnimationFrame(update);
}
}, { passive: true });
addEventListener("resize", () => {
current = null;
update();
});
update();
if (!motion) return;
// M4/M5: give each row's items their stagger, then reveal rows as they enter
const rows = [...document.querySelectorAll("main .row")];
rows.forEach((row) => {
const items = row.querySelectorAll(".project, .ledger > div, .row-text > *");
const step = row.id === "projects" ? 80 : row.querySelector(".ledger") ? 50 : 60;
items.forEach((el, i) => {
el.classList.add("reveal");
el.style.setProperty("--d", 150 + i * step + "ms");
});
});
function startReveals() {
const io = new IntersectionObserver((entries) => {
entries.forEach((e) => {
if (!e.isIntersecting) return;
e.target.classList.add("is-in");
io.unobserve(e.target);
});
}, { rootMargin: "0px 0px -12% 0px", threshold: 0.12 });
rows.forEach((row) => io.observe(row));
// M10: focus never lands on a row that hasn't revealed yet
rows.forEach((row) => row.addEventListener("focusin", () => {
row.classList.add("is-in");
io.unobserve(row);
}));
// M8: the pen signs the footer once, when it is 60% in view
const footer = document.querySelector(".site-footer");
if (footer && footer.querySelector(".signature")) {
const sign = new IntersectionObserver((entries) => {
if (!entries.some((e) => e.isIntersecting)) return;
footer.classList.add("is-signed");
sign.disconnect();
}, { threshold: 0.6 });
sign.observe(footer);
}
}
// wait for the loader to hand off, so nothing reveals behind it
if (root.classList.contains("is-loading")) {
const watch = new MutationObserver(() => {
if (!root.classList.contains("is-loading") || root.classList.contains("is-loaded")) {
watch.disconnect();
startReveals();
}
});
watch.observe(root, { attributes: true, attributeFilter: ["class"] });
} else {
startReveals();
}
})();
// M9 touch press: a tap lifts the row like a hover does, held 150ms after
// release so a quick tap still reads; starting a scroll drops it at once.
// M10 arrows: the ↗ is sent off when its link opens.
// M11 page transitions: mark the leaving page while a navigation runs (the
// arriving page marks itself in its head script).
(() => {
document.querySelectorAll(".project").forEach((project) => {
let timer = 0;
const release = (delay) => {
clearTimeout(timer);
timer = setTimeout(() => project.classList.remove("is-pressed"), delay);
};
project.addEventListener("pointerdown", (e) => {
if (e.pointerType === "mouse") return;
clearTimeout(timer);
project.classList.add("is-pressed");
});
project.addEventListener("pointerup", () => release(150));
project.addEventListener("pointercancel", () => release(0));
});
document.addEventListener("click", (e) => {
const arrow = e.target.closest && e.target.closest("a")?.querySelector(".arrow");
if (!arrow) return;
arrow.classList.remove("is-sent");
void arrow.offsetWidth; // restart if it is already playing
arrow.classList.add("is-sent");
arrow.addEventListener("animationend", () => arrow.classList.remove("is-sent"), { once: true });
});
const root = document.documentElement;
addEventListener("pageswap", (e) => {
if (e.viewTransition) root.classList.add("vt-page");
});
// coming back to this page from the back/forward cache
addEventListener("pageshow", (e) => {
if (e.persisted) root.classList.remove("vt-page");
});
})();
// Playground film: plays muted and looped while it's on screen, pauses when
// it scrolls away. With reduced motion it waits to be played. Play/pause and
// sound are buttons over the frame.
(() => {
const video = document.querySelector(".film-video");
if (!video) return;
const playBtn = document.querySelector(".film-play");
const soundBtn = document.querySelector(".film-sound");
const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)");
let userPaused = reduceMotion.matches; // with reduced motion, wait for a tap
let visible = false;
const label = () => {
playBtn.textContent = video.paused ? "play" : "pause";
// both buttons name what they'll do, not what's happening now
soundBtn.textContent = video.muted ? "sound on" : "sound off";
soundBtn.classList.toggle("is-on", !video.muted);
};
const update = () => {
if (visible && !userPaused) video.play().catch(() => {});
else video.pause();
};
playBtn.addEventListener("click", () => {
userPaused = !video.paused;
if (userPaused) video.pause();
else video.play().catch(() => {});
});
soundBtn.addEventListener("click", () => {
video.muted = !video.muted;
if (!video.muted && video.paused) {
userPaused = false;
video.play().catch(() => {});
}
});
["play", "pause", "volumechange"].forEach((type) => video.addEventListener(type, label));
// start loading a little before it scrolls in
new IntersectionObserver((entries) => {
if (entries.some((e) => e.isIntersecting)) video.preload = "auto";
}, { rootMargin: "400px 0px" }).observe(video);
new IntersectionObserver((entries) => {
visible = entries.some((e) => e.isIntersecting);
update();
}, { threshold: 0.5 }).observe(video);
document.addEventListener("visibilitychange", () => {
if (document.hidden) video.pause();
else update();
});
label();
})();