Repository navigation
Expand file tree
/
Copy pathfloat.js
More file actions
356 lines (325 loc) · 13.1 KB
/
Copy pathfloat.js
File metadata and controls
356 lines (325 loc) · 13.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
// T812 home — every Polaroid in the archive floats slowly by, like the words on
// the Woordeboek home screen. A ShuffleQueue (js/queue.js) walks the whole
// archive before repeating, so the photos buried deep in a semester get their
// turn too. Drag to scrub, fling to coast, hover to hold one, click to open it
// in the shared photo view (js/photobox.js).
(function () {
const field = document.getElementById("field");
const hint = document.getElementById("floatHint");
const nav = document.querySelector(".site-nav");
const plaque = document.querySelector(".plaque");
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
const PRELOAD = 5; // photos kept decoded and waiting off-screen
const FRICTION = 2.0; // how fast a fling coasts to a stop (per second)
const MAX_FLING = 2400; // px/s
let W = 0, H = 0, base = 200; // field size, base card width
let queue = null, total = 0;
const cards = []; // what's on screen
const ready = []; // decoded entries waiting to float in
const loading = new Set(); // keys being fetched
const met = new Set(); // every photo shown this visit
const decoded = []; // every entry that has loaded (fallback pool)
let velocity = 0; // shared fling velocity, px/s (+ = rightward)
let rafId = 0, lastT = 0;
const rand = (a, b) => a + Math.random() * (b - a);
const keyOf = (e) => e.it.file;
const isNamed = (it) => !/^\d/.test(it.title);
// ---------- sizing ----------
function measure() {
const top = nav.offsetHeight;
field.style.top = top + "px";
W = field.clientWidth;
H = field.clientHeight;
base = Math.max(110, Math.min(230, Math.min(W, H) * 0.26));
}
const wantCount = () => Math.max(5, Math.min(13, Math.round((W * H) / 110000)));
const bottomPad = () => (plaque ? plaque.offsetHeight + 28 : 30);
// ---------- loading photos ----------
function excluded() {
const s = new Set(loading);
cards.forEach((c) => s.add(keyOf(c.e)));
ready.forEach((e) => s.add(keyOf(e)));
return s;
}
function topUp() {
let guard = 0;
while (ready.length + loading.size < PRELOAD && guard++ < PRELOAD * 2) {
const e = queue.next(excluded());
if (!e || loading.has(keyOf(e))) return;
loading.add(keyOf(e));
const img = new Image();
img.decoding = "async";
img.alt = e.it.title;
img.draggable = false;
img.onload = () => {
loading.delete(keyOf(e));
e.img = img;
e.aspect = img.naturalWidth / img.naturalHeight || 0.63;
ready.push(e);
if (!decoded.includes(e)) decoded.push(e);
onReady();
};
img.onerror = () => { loading.delete(keyOf(e)); topUp(); };
img.src = e.it.file;
}
}
// the next photo to float in: a fresh one if decoded, else one seen before
function takeReady() {
let e = ready.shift();
if (!e) {
const on = new Set(cards.map((c) => keyOf(c.e)));
const pool = decoded.filter((d) => !on.has(keyOf(d)));
e = pool.length ? pool[Math.floor(Math.random() * pool.length)] : null;
}
topUp();
return e;
}
// while the field is still filling up, each decoded photo drops straight in
function onReady() {
if (cards.length < wantCount()) {
const e = ready.shift();
spawn(e, rand(0, Math.max(1, W - base)), true);
topUp();
}
updateHint();
}
// ---------- cards ----------
function sizeFor(e, depth) {
const scale = 0.58 + 0.42 * depth;
const w = base * scale * (e.aspect > 1 ? 1.45 : 1); // sideways Polaroids get wider
return { w, h: w / e.aspect };
}
const minY = () => 12;
const maxY = (h) => Math.max(minY() + 1, H - bottomPad() - h * 0.55);
function pickY(x, w, h, skip) {
const lo = minY(), hi = maxY(h);
let best = rand(lo, hi), bestHits = Infinity;
for (let i = 0; i < 16; i++) {
const y = rand(lo, hi);
let hits = 0;
for (const o of cards) {
if (o === skip) continue;
const ox = !(x + w + 24 < o.x || o.x + o.w + 24 < x);
const oy = !(y + h + 18 < o.y || o.y + o.h + 18 < y);
if (ox && oy) hits++;
}
if (hits < bestHits) { best = y; bestHits = hits; }
if (hits === 0) break;
}
return best;
}
function spawn(e, x, fadeIn) {
const el = document.createElement("button");
el.className = "floater" + (fadeIn ? " enter" : "");
el.type = "button";
el.innerHTML = `<span class="fcard"></span><span class="fcap"></span>`;
const c = { el, e: null, x, y: 0, w: 0, h: 0, depth: 0, speed: 0, hold: 1, hovered: false };
el.addEventListener("pointerenter", (ev) => { if (ev.pointerType === "mouse") c.hovered = true; });
el.addEventListener("pointerleave", () => { c.hovered = false; });
el.addEventListener("focus", () => { c.hovered = true; });
el.addEventListener("blur", () => { c.hovered = false; });
el.addEventListener("click", () => {
if (justDragged) return;
stop(); // nothing needs to move behind the photo view
PhotoBox.open(c.e.it, c.e.coll);
});
field.appendChild(el);
cards.push(c);
dress(c, e, x);
return c;
}
// put a (new) photo on a card and give it a fresh depth, speed, tilt and lane
function dress(c, e, x) {
c.e = e;
const far = Math.random() < 0.4;
c.depth = far ? rand(0.05, 0.4) : rand(0.62, 1);
c.speed = 14 + c.depth * 30; // nearer = faster (parallax)
const { w, h } = sizeFor(e, c.depth);
c.w = w; c.h = h; c.x = x;
c.y = pickY(x, w, h, c);
const card = c.el.firstChild;
card.replaceChildren(e.img);
card.style.setProperty("--tilt", `${rand(-6, 6).toFixed(1)}deg`);
c.el.lastChild.textContent = isNamed(e.it) ? e.it.title : "";
c.el.style.width = w + "px";
c.el.style.opacity = far ? (0.45 + c.depth * 0.6).toFixed(2) : "1";
c.el.style.zIndex = String(1 + Math.round(c.depth * 10));
c.el.setAttribute("aria-label", `Open ${e.it.title}`);
met.add(keyOf(e));
place(c);
}
function place(c) {
c.el.style.transform = `translate3d(${c.x.toFixed(1)}px, ${c.y.toFixed(1)}px, 0)`;
}
// a card that has drifted (or been flung) off one edge comes back on the other
// as the next photo in the shuffle. `dx` is how it just moved: only the edge
// it is travelling towards counts, so a card waiting just off the right edge
// to drift in isn't mistaken for one that was flung out that side.
function recycle(c, dx) {
if (dx <= 0 && c.x + c.w < -60) {
const e = takeReady();
if (e) dress(c, e, W + rand(20, 160));
else c.x = W + rand(20, 160);
} else if (dx > 0 && c.x > W + 60) {
const e = takeReady();
if (e) dress(c, e, 0);
c.x = -c.w - rand(20, 160);
}
}
// ---------- motion ----------
const parallax = (c) => 0.55 + 0.45 * c.depth;
function tick(t) {
rafId = requestAnimationFrame(tick);
const dt = Math.min(0.05, (t - lastT) / 1000 || 0);
lastT = t;
if (!dragging) {
const drift = reduceMotion.matches ? 0 : 1;
for (const c of cards) {
// a hovered card eases to a stop and eases off again when you leave it
const target = c.hovered ? 0 : 1;
c.hold += (target - c.hold) * Math.min(1, dt * 6);
const dx = (-c.speed * drift * c.hold + velocity * parallax(c)) * dt;
c.x += dx;
recycle(c, dx);
}
velocity *= Math.max(0, 1 - FRICTION * dt);
if (Math.abs(velocity) < 2) velocity = 0;
}
separate(dt);
for (const c of cards) place(c);
}
// Nearer cards drift faster, so they catch up with slower ones. Instead of
// letting them stack, overlapping cards slide apart vertically, faster the
// more they overlap. A held (hovered) card stays put and the other one moves
// round it. Cards at very different depths push each other less, since the
// faded far ones read as background anyway.
function separate(dt) {
const PAD = 18;
for (let i = 0; i < cards.length; i++) {
const a = cards[i];
for (let j = i + 1; j < cards.length; j++) {
const b = cards[j];
const ox = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x) + PAD;
const oy = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y) + PAD;
if (ox <= 0 || oy <= 0) continue;
const weight = Math.abs(a.depth - b.depth) > 0.35 ? 0.5 : 1;
const aShare = a.hovered ? 0 : b.hovered ? 1 : 0.5;
// first choice: slide apart vertically
const stepY = Math.min(oy * 3, 240) * weight * dt;
const up = a.y + a.h / 2 <= b.y + b.h / 2 ? -1 : 1; // a is above → a goes up
const ay0 = a.y, by0 = b.y;
a.y = clampY(a, a.y + up * stepY * aShare);
b.y = clampY(b, b.y - up * stepY * (1 - aShare));
const moved = Math.abs(a.y - ay0) + Math.abs(b.y - by0);
// pinned against the top or bottom: separate sideways instead, which
// makes the faster card hang back behind the slower one
if (moved < stepY * 0.5) {
const stepX = Math.min(ox * 3, 240) * weight * dt;
const left = a.x + a.w / 2 <= b.x + b.w / 2 ? -1 : 1;
a.x += left * stepX * aShare;
b.x -= left * stepX * (1 - aShare);
}
}
}
}
const clampY = (c, y) => Math.max(minY(), Math.min(maxY(c.h), y));
function start() {
if (rafId || document.hidden || PhotoBox.isOpen()) return;
lastT = performance.now();
rafId = requestAnimationFrame(tick);
}
function stop() { cancelAnimationFrame(rafId); rafId = 0; }
// ---------- drag / fling ----------
let dragging = false, pointerDown = false, justDragged = false;
let startX = 0, lastX = 0, samples = [];
field.addEventListener("pointerdown", (ev) => {
if (ev.button !== 0) return;
pointerDown = true; justDragged = false;
startX = lastX = ev.clientX;
samples = [{ t: ev.timeStamp, x: ev.clientX }];
velocity = 0;
});
window.addEventListener("pointermove", (ev) => {
if (!pointerDown) return;
if (!dragging && Math.abs(ev.clientX - startX) > 6) {
dragging = true;
field.classList.add("dragging");
}
if (!dragging) return;
const dx = ev.clientX - lastX;
lastX = ev.clientX;
for (const c of cards) { c.x += dx * parallax(c); recycle(c, dx); place(c); }
samples.push({ t: ev.timeStamp, x: ev.clientX });
while (samples.length > 2 && ev.timeStamp - samples[0].t > 100) samples.shift();
});
function endDrag(ev) {
if (!pointerDown) return;
pointerDown = false;
if (!dragging) return;
dragging = false;
justDragged = true; // swallow the click that follows
setTimeout(() => { justDragged = false; }, 0);
field.classList.remove("dragging");
const first = samples[0], lastS = samples[samples.length - 1];
const span = (ev.timeStamp - first.t) / 1000;
if (!reduceMotion.matches && span > 0 && ev.timeStamp - lastS.t < 80) {
velocity = Math.max(-MAX_FLING, Math.min(MAX_FLING, (lastS.x - first.x) / span));
}
lastT = performance.now();
}
window.addEventListener("pointerup", endDrag);
window.addEventListener("pointercancel", endDrag);
// trackpad / mouse wheel nudges the stream too
field.addEventListener("wheel", (ev) => {
ev.preventDefault();
const d = Math.abs(ev.deltaX) > Math.abs(ev.deltaY) ? ev.deltaX : ev.deltaY;
velocity = Math.max(-MAX_FLING, Math.min(MAX_FLING, velocity - d * 6));
}, { passive: false });
document.addEventListener("keydown", (ev) => {
if (PhotoBox.isOpen() || ev.target.closest("input, textarea")) return;
if (ev.key === "ArrowLeft") velocity = Math.max(-MAX_FLING, velocity - 500);
if (ev.key === "ArrowRight") velocity = Math.min(MAX_FLING, velocity + 500);
});
// ---------- lifecycle ----------
document.addEventListener("visibilitychange", () => (document.hidden ? stop() : start()));
PhotoBox.onClose(start);
let resizeTimer = 0;
window.addEventListener("resize", () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
measure();
for (const c of cards) {
const { w, h } = sizeFor(c.e, c.depth);
c.w = w; c.h = h; c.el.style.width = w + "px";
c.y = Math.min(c.y, maxY(h));
place(c);
}
while (cards.length > wantCount()) cards.pop().el.remove();
while (cards.length < wantCount()) {
const e = takeReady();
if (!e) break;
spawn(e, rand(0, W), true);
}
}, 150);
});
function updateHint() {
if (!total) return;
hint.textContent = `${total} polaroids drifting by · you've met ${met.size}`;
}
// ---------- go ----------
measure();
fetch("manifest.json")
.then((r) => r.json())
.then((d) => {
const entries = [];
d.collections.forEach((coll) =>
coll.items.filter((it) => it.kind === "image").forEach((it) => entries.push({ it, coll })));
total = entries.length;
if (!total) { hint.textContent = "no polaroids yet"; return; }
queue = new ShuffleQueue(entries, keyOf);
topUp();
start();
setInterval(updateHint, 1000);
})
.catch(() => { hint.textContent = "couldn't load the archive"; });
})();