-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathanimations-gallery.js
More file actions
752 lines (679 loc) · 25.7 KB
/
Copy pathanimations-gallery.js
File metadata and controls
752 lines (679 loc) · 25.7 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
// /animations — public animation gallery.
//
// Surfaces three sources in one searchable, filterable grid:
// • Community clips published by three.ws users (GET /api/animations/clips
// ?include_public=true&visibility=public). Appear first, newest-first.
// • The built-in three.ws motion library (/animations/manifest.json) — the
// same curated clips the /pose studio ships with. Always present.
// • The full motion library (GET /api/animations/library) — the complete
// Mixamo-sourced catalog (2,800+ clips) hosted on the R2 CDN.
//
// All are normalized to one card shape — poster thumbnail, derived category
// (src/animation-categories.js), duration, loop mode — then filtered (search +
// category + loop/once), sorted, and paginated client-side (PAGE_SIZE at a time,
// infinite-scroll, lazy thumbnails). The full catalog is fetched from the CDN in
// bounded pages (LIBRARY_PAGE_SIZE) rather than one large response, so a library
// that grows past thousands of clips never lands as a single unbounded payload.
//
// Previews run through ONE shared WebGL engine (src/animations-live-preview.js):
// hovering a card (or opening the detail modal) moves the singleton canvas into
// that card and plays the retargeted clip on the preview avatar. No iframes,
// no per-card GL contexts, nothing 3D loaded until the first preview.
//
// Deep links: ?clip=<id> opens the detail modal; q/cat/filter/sort round-trip
// through the URL so filtered views are shareable.
import { GALLERY_CATEGORIES, galleryCategoryOf } from './animation-categories.js';
import { getLivePreview } from './animations-live-preview.js';
const API_BASE = '/api/animations/clips';
const MANIFEST_URL = '/animations/manifest.json';
const LIBRARY_API = '/api/animations/library';
const PAGE_SIZE = 36;
// Cap community pagination so a large catalog can't stall first paint.
const COMMUNITY_MAX = 300;
// Page size for the full CDN catalog fetch. Matches the endpoint's max page so
// each response stays bounded (~400 KB) as the library grows past thousands of
// clips, instead of one ever-growing blob. A hard ceiling of pages guards
// against a runaway manifest.
const LIBRARY_PAGE_SIZE = 1000;
const LIBRARY_MAX_PAGES = 50;
const HOVER_DELAY_MS = 130;
const REDUCED_MOTION = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
const TOUCH_ONLY = window.matchMedia?.('(hover: none)').matches;
const $ = (role) => document.querySelector(`[data-role="${role}"]`);
const els = {
loading: $('loading'),
grid: $('grid'),
empty: $('empty'),
emptySearch: $('empty-search'),
emptySearchMsg: $('empty-search-msg'),
clearSearch: $('clear-search'),
error: $('error'),
retry: $('retry'),
search: $('search'),
chips: $('chips'),
typeFilter: $('type-filter'),
sort: $('sort'),
count: $('count'),
heroStats: $('hero-stats'),
loadMore: $('load-more'),
loadMoreBtn: $('load-more-btn'),
sentinel: $('sentinel'),
// Detail modal
modal: $('modal'),
modalStage: $('modal-stage'),
modalSpinner: $('modal-spinner'),
modalTitle: $('modal-title'),
modalMeta: $('modal-meta'),
modalTags: $('modal-tags'),
modalStudio: $('modal-studio'),
modalCopyLink: $('modal-copy-link'),
modalCopyEmbed: $('modal-copy-embed'),
modalPlay: $('modal-play'),
modalSpeed: $('modal-speed'),
modalSpeedVal: $('modal-speed-val'),
modalScrub: $('modal-scrub'),
modalTime: $('modal-time'),
modalClose: $('modal-close'),
modalPrev: $('modal-prev'),
modalNext: $('modal-next'),
modalError: $('modal-error'),
};
const params = new URLSearchParams(location.search);
const state = {
query: params.get('q') || '',
filter: params.get('filter') || '', // '' | loop | once
category: params.get('cat') || '', // '' | GALLERY_CATEGORIES key
sort: params.get('sort') || 'featured',
all: [],
filtered: [],
shown: 0,
loaded: false,
modalIndex: -1, // index into state.filtered while the modal is open
};
const live = getLivePreview();
if (state.query) els.search.value = state.query;
if (els.sort) els.sort.value = state.sort;
// ── URL state ──────────────────────────────────────────────────────────────
function syncUrl(clipId) {
const p = new URLSearchParams();
if (state.query) p.set('q', state.query);
if (state.category) p.set('cat', state.category);
if (state.filter) p.set('filter', state.filter);
if (state.sort !== 'featured') p.set('sort', state.sort);
if (clipId) p.set('clip', clipId);
const qs = p.toString();
const next = qs ? `${location.pathname}?${qs}` : location.pathname;
if (next !== location.pathname + location.search) history.replaceState(null, '', next);
}
// ── Fetch + normalize ───────────────────────────────────────────────────────
async function fetchLibrary() {
const res = await fetch(MANIFEST_URL, { cache: 'force-cache' });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const manifest = await res.json();
if (!Array.isArray(manifest)) return [];
return manifest.map(normalizeLibraryClip);
}
async function fetchCommunity() {
const out = [];
let cursor = null;
while (out.length < COMMUNITY_MAX) {
const p = new URLSearchParams({ include_public: 'true', visibility: 'public', limit: '50' });
if (cursor) p.set('cursor', cursor);
const res = await fetch(`${API_BASE}?${p}`, { credentials: 'include' });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
const incoming = Array.isArray(data.items) ? data.items : [];
out.push(...incoming);
cursor = data.next_cursor || null;
if (!cursor || incoming.length === 0) break;
}
return out.slice(0, COMMUNITY_MAX).map(normalizeCommunityClip);
}
async function fetchFullLibrary() {
// Page through the catalog with the endpoint's opt-in ?limit/?offset so each
// response is bounded and individually CDN-cacheable. The endpoint returns
// `next_offset: null` on the last page; the page ceiling is a runaway guard.
const out = [];
let offset = 0;
for (let i = 0; i < LIBRARY_MAX_PAGES; i++) {
const res = await fetch(`${LIBRARY_API}?limit=${LIBRARY_PAGE_SIZE}&offset=${offset}`, {
cache: 'force-cache',
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
const clips = Array.isArray(data.clips) ? data.clips : [];
out.push(...clips);
if (data.next_offset == null || clips.length === 0) break;
offset = data.next_offset;
}
return out.map(normalizeFullLibraryClip);
}
function normalizeLibraryClip(clip) {
return {
id: clip.name,
source: 'library',
name: clip.label || clip.name,
loop: clip.loop !== false,
icon: clip.icon || '🎬',
tags: [],
category: galleryCategoryOf(clip.name, clip.label),
duration_ms: clip.duration ? Math.round(clip.duration * 1000) : null,
url: clip.url, // site-relative clip JSON — playable by the live preview
thumbnail_url: `/animations/thumbs/${encodeURIComponent(clip.name)}.webp`,
price: null,
};
}
function normalizeFullLibraryClip(clip) {
return {
id: clip.name,
source: 'mixamo',
name: clip.label || clip.name,
loop: clip.loop !== false,
icon: clip.icon || '🎬',
tags: clip.category ? [clip.category] : [],
category: galleryCategoryOf(clip.name, clip.label),
duration_ms: clip.duration ? Math.round(clip.duration * 1000) : null,
url: clip.url, // absolute CDN url
// The library manifest publishes a `thumb` url per clip; older manifests
// predate thumbnails, so fall back to the CDN convention (thumbs live
// beside clips) and let the card's onerror show the icon placeholder.
thumbnail_url:
clip.thumb ||
(clip.url ? clip.url.replace('/clips/', '/thumbs/').replace(/\.json$/, '.webp') : null),
price: null,
};
}
function normalizeCommunityClip(clip) {
return {
id: clip.id,
source: 'community',
name: clip.name || 'Untitled',
loop: clip.loop !== false,
icon: '🎬',
tags: Array.isArray(clip.tags) ? clip.tags : [],
category: galleryCategoryOf(clip.id, clip.name),
duration_ms: clip.duration_ms || null,
url: null, // fetched through /api/animations/clips/:id by the preview engine
thumbnail_url: clip.thumbnail_url || null,
price: clip.price || null,
};
}
async function loadAll() {
showState('loading');
const [libRes, comRes, fullRes] = await Promise.allSettled([
fetchLibrary(),
fetchCommunity(),
fetchFullLibrary(),
]);
if (libRes.status === 'rejected' && comRes.status === 'rejected' && fullRes.status === 'rejected') {
showState('error');
return;
}
const library = libRes.status === 'fulfilled' ? libRes.value : [];
const community = comRes.status === 'fulfilled' ? comRes.value : [];
const full = fullRes.status === 'fulfilled' ? fullRes.value : [];
// Community clips lead (fresh, human-authored); the curated library follows;
// the full catalog trails, minus anything the curated set already surfaces.
const curatedNames = new Set(library.map((c) => c.id));
state.all = [...community, ...library, ...full.filter((c) => !curatedNames.has(c.id))];
state.loaded = true;
renderHeroStats();
renderChips();
applyFilters();
// ?clip= deep link → open the modal once data exists.
const wanted = new URLSearchParams(location.search).get('clip');
if (wanted) {
const idx = state.filtered.findIndex((c) => c.id === wanted);
if (idx >= 0) openModal(idx);
else {
const item = state.all.find((c) => c.id === wanted);
if (item) {
// Visible under different filters — clear them so the link works.
state.query = '';
state.category = '';
state.filter = '';
els.search.value = '';
renderChips();
applyFilters();
openModal(state.filtered.findIndex((c) => c.id === wanted));
}
}
}
}
// ── Hero stats + chips ───────────────────────────────────────────────────────
function renderHeroStats() {
if (!els.heroStats) return;
const total = state.all.length;
const community = state.all.filter((c) => c.source === 'community').length;
const cats = new Set(state.all.map((c) => c.category)).size;
els.heroStats.textContent = `${total.toLocaleString()} clips · ${cats} categories${
community ? ` · ${community} community-authored` : ''
}`;
}
function renderChips() {
if (!els.chips) return;
const counts = new Map();
for (const item of state.all) counts.set(item.category, (counts.get(item.category) || 0) + 1);
els.chips.innerHTML = '';
const mk = (key, label, icon, count) => {
const btn = document.createElement('button');
btn.className = 'ag-chip';
btn.setAttribute('role', 'tab');
btn.dataset.cat = key;
btn.setAttribute('aria-selected', String(state.category === key));
btn.innerHTML = `${icon ? `<span aria-hidden="true">${icon}</span> ` : ''}${escHtml(label)}${
count != null ? ` <span class="ag-chip-count">${count.toLocaleString()}</span>` : ''
}`;
els.chips.appendChild(btn);
};
mk('', 'All', '', state.all.length);
for (const cat of GALLERY_CATEGORIES) {
const n = counts.get(cat.key);
if (n) mk(cat.key, cat.label, cat.icon, n);
}
}
function syncChips() {
els.chips?.querySelectorAll('[data-cat]').forEach((btn) => {
btn.setAttribute('aria-selected', String(btn.dataset.cat === state.category));
});
}
// ── Filter + sort + render ───────────────────────────────────────────────────
function applyFilters() {
const q = state.query.toLowerCase();
state.filtered = state.all.filter((item) => {
if (state.filter === 'loop' && !item.loop) return false;
if (state.filter === 'once' && item.loop) return false;
if (state.category && item.category !== state.category) return false;
if (q) {
const hay = `${item.name} ${item.tags.join(' ')} ${item.category}`.toLowerCase();
if (!hay.includes(q)) return false;
}
return true;
});
sortFiltered();
state.shown = 0;
renderCount();
renderGrid();
}
function sortFiltered() {
const arr = state.filtered;
switch (state.sort) {
case 'az':
arr.sort((a, b) => a.name.localeCompare(b.name));
break;
case 'za':
arr.sort((a, b) => b.name.localeCompare(a.name));
break;
case 'shortest':
arr.sort((a, b) => (a.duration_ms ?? 1e9) - (b.duration_ms ?? 1e9));
break;
case 'longest':
arr.sort((a, b) => (b.duration_ms ?? -1) - (a.duration_ms ?? -1));
break;
case 'shuffle': {
// Deterministic per page load, reshuffled when re-selected.
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
break;
}
default:
// 'featured' — the assembled source order (community → curated → catalog).
break;
}
}
function renderCount() {
if (!els.count) return;
if (!state.loaded) {
els.count.textContent = '';
return;
}
const n = state.filtered.length;
els.count.textContent = n === state.all.length
? `${n.toLocaleString()} animations`
: `${n.toLocaleString()} of ${state.all.length.toLocaleString()}`;
}
function renderGrid() {
if (state.filtered.length === 0) {
if (state.all.length === 0) {
showState('empty');
} else {
showState('empty-search');
if (els.emptySearchMsg) {
els.emptySearchMsg.textContent = state.query
? `No animations match “${state.query}”.`
: 'No animations match these filters.';
}
}
return;
}
showState('grid');
const start = state.shown;
const end = Math.min(start + PAGE_SIZE, state.filtered.length);
if (start === 0) {
live.stop();
els.grid.innerHTML = '';
}
const fragment = document.createDocumentFragment();
for (let i = start; i < end; i++) {
fragment.appendChild(buildCard(state.filtered[i], i));
}
els.grid.appendChild(fragment);
state.shown = end;
els.loadMore.hidden = state.shown >= state.filtered.length;
}
function showMore() {
if (state.shown < state.filtered.length) renderGrid();
}
function fmtDuration(ms) {
if (ms == null) return '';
const s = ms / 1000;
if (s < 60) return `${s.toFixed(1)}s`;
const m = Math.floor(s / 60);
return `${m}m ${Math.round(s % 60)}s`;
}
const CATEGORY_BY_KEY = new Map(GALLERY_CATEGORIES.map((c) => [c.key, c]));
function sourceLabel(source) {
return source === 'community' ? 'Community' : source === 'mixamo' ? 'Mocap' : 'Studio';
}
// ── Card ────────────────────────────────────────────────────────────────────
function buildCard(clip, index) {
const card = document.createElement('article');
card.className = 'ag-card';
card.dataset.index = String(index);
const cat = CATEGORY_BY_KEY.get(clip.category);
const studioUrl = `/pose?anim=${encodeURIComponent(clip.id)}`;
card.innerHTML = `
<div class="ag-card-preview" role="button" tabindex="0"
aria-label="${escHtml(clip.name)} — open details">
${clip.thumbnail_url
? `<img class="ag-card-thumb" src="${escHtml(clip.thumbnail_url)}" alt="" loading="lazy" decoding="async" />`
: ''}
<div class="ag-card-thumb-fallback" aria-hidden="true" ${clip.thumbnail_url ? 'hidden' : ''}>${escHtml(clip.icon || '🎬')}</div>
<div class="ag-card-live" aria-hidden="true"></div>
<span class="ag-card-duration">${fmtDuration(clip.duration_ms)}</span>
${clip.loop ? '' : '<span class="ag-card-once" title="Plays once">once</span>'}
${clip.price ? `<span class="ag-card-price">$${(Number(clip.price.amount) / 1_000_000).toFixed(2)}</span>` : ''}
</div>
<div class="ag-card-meta">
<h3 class="ag-card-title" title="${escHtml(clip.name)}">${escHtml(clip.name)}</h3>
<div class="ag-card-sub">
<button class="ag-card-cat" data-cat-jump="${escHtml(clip.category)}"
title="Show all ${escHtml(cat?.label || 'More')} animations">${cat?.icon || ''} ${escHtml(cat?.label || 'More')}</button>
<span class="ag-card-source">${sourceLabel(clip.source)}</span>
</div>
<div class="ag-card-actions">
<a href="${escHtml(studioUrl)}" class="ag-card-btn ag-card-btn--primary"
title="Open this animation in the Studio to remix or apply to your avatar">Open in Studio</a>
<button class="ag-card-btn" data-details
aria-label="Details and preview for ${escHtml(clip.name)}">Details</button>
</div>
</div>
`;
const previewZone = card.querySelector('.ag-card-preview');
const liveHost = card.querySelector('.ag-card-live');
const img = card.querySelector('.ag-card-thumb');
const fallback = card.querySelector('.ag-card-thumb-fallback');
if (img && fallback) {
img.addEventListener('error', () => {
img.remove();
fallback.hidden = false;
});
}
// Hover → live preview through the shared engine (skipped for touch and
// reduced-motion users; both get the full preview in the details modal).
if (!TOUCH_ONLY && !REDUCED_MOTION) {
let hoverTimer = 0;
previewZone.addEventListener('mouseenter', () => {
hoverTimer = setTimeout(() => {
card.classList.add('is-loading-preview');
live
.play(liveHost, clip)
.then(() => {
if (live.active === clip) card.classList.add('is-live');
})
.catch(() => {})
.finally(() => card.classList.remove('is-loading-preview'));
}, HOVER_DELAY_MS);
});
previewZone.addEventListener('mouseleave', () => {
clearTimeout(hoverTimer);
card.classList.remove('is-live', 'is-loading-preview');
if (live.active === clip) live.stop();
});
}
const open = () => openModal(index);
previewZone.addEventListener('click', open);
previewZone.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
open();
}
});
card.querySelector('[data-details]').addEventListener('click', open);
card.querySelector('[data-cat-jump]').addEventListener('click', (e) => {
state.category = e.currentTarget.dataset.catJump || '';
syncChips();
syncUrl();
applyFilters();
window.scrollTo({ top: 0, behavior: 'smooth' });
});
return card;
}
function escHtml(s) {
return String(s ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
// ── Detail modal ─────────────────────────────────────────────────────────────
function openModal(index) {
const clip = state.filtered[index];
if (!clip || !els.modal) return;
state.modalIndex = index;
els.modalTitle.textContent = clip.name;
const cat = CATEGORY_BY_KEY.get(clip.category);
els.modalMeta.innerHTML = [
cat ? `${cat.icon} ${escHtml(cat.label)}` : null,
clip.duration_ms ? escHtml(fmtDuration(clip.duration_ms)) : null,
clip.loop ? 'loops' : 'plays once',
escHtml(sourceLabel(clip.source)),
]
.filter(Boolean)
.map((x) => `<span>${x}</span>`)
.join('<span class="ag-dot" aria-hidden="true">·</span>');
els.modalTags.innerHTML = clip.tags?.length
? clip.tags.slice(0, 8).map((t) => `<span class="ag-tag">${escHtml(t)}</span>`).join('')
: '';
els.modalStudio.href = `/pose?anim=${encodeURIComponent(clip.id)}`;
els.modalError.hidden = true;
els.modalSpinner.hidden = false;
els.modalPrev.disabled = index <= 0;
els.modalNext.disabled = index >= state.filtered.length - 1;
// Transport defaults.
els.modalSpeed.value = '1';
els.modalSpeedVal.textContent = '1×';
els.modalScrub.value = '0';
setPlayIcon(false);
els.modal.hidden = false;
document.body.style.overflow = 'hidden';
els.modalClose.focus();
syncUrl(clip.id);
let scrubbing = false;
els.modalScrub.oninput = () => {
scrubbing = true;
live.seek(Number(els.modalScrub.value) / 1000);
};
els.modalScrub.onchange = () => {
scrubbing = false;
};
live
.play(els.modalStage, clip, {
onFrame: (t, d) => {
if (!scrubbing && d > 0) {
els.modalScrub.value = String(Math.round(((t % d) / d) * 1000));
els.modalTime.textContent = `${(t % d).toFixed(1)}s / ${d.toFixed(1)}s`;
}
},
})
.then(() => {
els.modalSpinner.hidden = true;
live.refit();
})
.catch(() => {
els.modalSpinner.hidden = true;
els.modalError.hidden = false;
});
}
function closeModal() {
if (els.modal.hidden) return;
els.modal.hidden = true;
document.body.style.overflow = '';
live.stop();
state.modalIndex = -1;
syncUrl();
}
function stepModal(delta) {
const next = state.modalIndex + delta;
if (next < 0 || next >= state.filtered.length) return;
// Ensure the card list has rendered far enough that "next" stays in sync
// with what the user returns to after closing.
while (state.shown <= next && state.shown < state.filtered.length) showMore();
openModal(next);
}
function setPlayIcon(paused) {
els.modalPlay.innerHTML = paused
? '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><polygon points="5 3 19 12 5 21 5 3"/></svg>'
: '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="5" y="4" width="5" height="16"/><rect x="14" y="4" width="5" height="16"/></svg>';
els.modalPlay.setAttribute('aria-label', paused ? 'Play' : 'Pause');
}
els.modalPlay?.addEventListener('click', () => {
const paused = !live.isPaused();
live.setPaused(paused);
setPlayIcon(paused);
});
els.modalSpeed?.addEventListener('input', () => {
const f = Number(els.modalSpeed.value);
live.setSpeed(f);
els.modalSpeedVal.textContent = `${f}×`;
});
els.modalClose?.addEventListener('click', closeModal);
els.modalPrev?.addEventListener('click', () => stepModal(-1));
els.modalNext?.addEventListener('click', () => stepModal(1));
els.modal?.addEventListener('click', (e) => {
if (e.target === els.modal) closeModal();
});
els.modalCopyLink?.addEventListener('click', async () => {
const clip = state.filtered[state.modalIndex];
if (!clip) return;
const url = `${location.origin}/animations?clip=${encodeURIComponent(clip.id)}`;
await navigator.clipboard.writeText(url).catch(() => {});
flashButton(els.modalCopyLink, 'Copied!');
});
els.modalCopyEmbed?.addEventListener('click', async () => {
const clip = state.filtered[state.modalIndex];
if (!clip) return;
const src = `${location.origin}/embed/avatar?anim=${encodeURIComponent(clip.id)}`;
const snippet = `<iframe src="${src}" width="360" height="480" style="border:0;border-radius:12px" allow="autoplay" title="${clip.name} — three.ws"></iframe>`;
await navigator.clipboard.writeText(snippet).catch(() => {});
flashButton(els.modalCopyEmbed, 'Copied!');
});
function flashButton(btn, msg) {
const prev = btn.textContent;
btn.textContent = msg;
btn.disabled = true;
setTimeout(() => {
btn.textContent = prev;
btn.disabled = false;
}, 1200);
}
// ── State display ──────────────────────────────────────────────────────────
function showState(which) {
els.loading.hidden = which !== 'loading';
els.grid.hidden = which !== 'grid';
els.empty.hidden = which !== 'empty';
els.emptySearch.hidden = which !== 'empty-search';
els.error.hidden = which !== 'error';
if (which !== 'grid') els.loadMore.hidden = true;
}
// ── Controls ───────────────────────────────────────────────────────────────
let searchDebounce;
els.search?.addEventListener('input', () => {
clearTimeout(searchDebounce);
searchDebounce = setTimeout(() => {
state.query = els.search.value.trim();
syncUrl();
if (state.loaded) applyFilters();
}, 180);
});
els.chips?.addEventListener('click', (e) => {
const btn = e.target.closest('[data-cat]');
if (!btn) return;
state.category = btn.dataset.cat;
syncChips();
syncUrl();
if (state.loaded) applyFilters();
});
els.typeFilter?.addEventListener('click', (e) => {
const btn = e.target.closest('[data-filter]');
if (!btn) return;
state.filter = btn.dataset.filter;
els.typeFilter.querySelectorAll('[data-filter]').forEach((b) => {
b.setAttribute('aria-pressed', String(b === btn));
});
syncUrl();
if (state.loaded) applyFilters();
});
els.sort?.addEventListener('change', () => {
state.sort = els.sort.value;
syncUrl();
if (state.loaded) applyFilters();
});
els.clearSearch?.addEventListener('click', () => {
state.query = '';
state.filter = '';
state.category = '';
els.search.value = '';
els.typeFilter?.querySelectorAll('[data-filter]').forEach((b) => {
b.setAttribute('aria-pressed', String(b.dataset.filter === ''));
});
syncChips();
syncUrl();
if (state.loaded) applyFilters();
});
els.retry?.addEventListener('click', () => loadAll());
els.loadMoreBtn?.addEventListener('click', showMore);
// Infinite scroll sentinel.
if ('IntersectionObserver' in window && els.sentinel) {
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) showMore();
},
{ rootMargin: '600px' },
);
observer.observe(els.sentinel);
}
// ── Keyboard ────────────────────────────────────────────────────────────────
document.addEventListener('keydown', (e) => {
if (!els.modal.hidden) {
if (e.key === 'Escape') closeModal();
else if (e.key === 'ArrowLeft') stepModal(-1);
else if (e.key === 'ArrowRight') stepModal(1);
else if (e.key === ' ' && e.target === document.body) {
e.preventDefault();
els.modalPlay.click();
}
return;
}
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName || '');
if (e.key === '/' && !typing) {
e.preventDefault();
els.search.focus();
} else if (e.key === 'Escape' && typing && document.activeElement === els.search) {
els.search.blur();
}
});
// ── Boot ───────────────────────────────────────────────────────────────────
loadAll();