-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathselfie-capture.js
More file actions
741 lines (668 loc) · 25.3 KB
/
Copy pathselfie-capture.js
File metadata and controls
741 lines (668 loc) · 25.3 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
/**
* Selfie capture flow — entry for /create/selfie.
*
* Hero slot (frontal) is required. Side slots (left / right) are optional —
* they live under the "Add side angles" disclosure and bump reconstruction
* fidelity when supplied. Capture method (camera vs upload) is picked per slot.
*
* On submit, dispatches a `selfie:submit` CustomEvent on document with
* detail = { files: { frontal, left?, right? }, bodyType, avatarType, method }
* which the selfie pipeline picks up to drive avatar reconstruction.
*
* Camera overlay uses the face-quality engine for real-time 468-point wireframe,
* head-pose estimation, blur/lighting/centering quality gates.
*/
import { createQualitySession, preload, SLOT_PRESETS } from './face-quality.js';
import { log } from './shared/log.js';
const REQUIRED_SLOT = 'frontal';
const OPTIONAL_SLOTS = /** @type {const} */ (['left', 'right']);
const ALL_SLOTS = /** @type {const} */ ([REQUIRED_SLOT, ...OPTIONAL_SLOTS]);
const ETA_FAST_SEC = 90;
const ETA_HIGH_SEC = 120;
const state = {
bodyType: /** @type {'male' | 'female'} */ ('male'),
avatarType: /** @type {'v1' | 'v2'} */ ('v1'),
files: /** @type {Record<string, File | null>} */ ({ frontal: null, left: null, right: null }),
lastMethod: /** @type {'camera' | 'upload' | null} */ (null),
};
const cameraSupported =
typeof navigator !== 'undefined' &&
!!navigator.mediaDevices &&
typeof navigator.mediaDevices.getUserMedia === 'function';
// ── DOM refs ───────────────────────────────────────────────────────────────
const backBtn = /** @type {HTMLButtonElement} */ (document.getElementById('back-btn'));
const unsupportedMsg = document.getElementById('unsupported-msg');
const heroSlot = /** @type {HTMLElement | null} */ (
document.querySelector('.hero-slot[data-slot="frontal"]')
);
const heroCameraBtn = /** @type {HTMLButtonElement | null} */ (
document.querySelector('.hero-pill[data-action="open-camera"]')
);
const heroUploadBtn = /** @type {HTMLButtonElement | null} */ (
document.querySelector('.hero-pill[data-action="open-upload"]')
);
const sideFrames = /** @type {NodeListOf<HTMLElement>} */ (
document.querySelectorAll('.slot-frame[data-slot]')
);
const slotInputs = /** @type {NodeListOf<HTMLInputElement>} */ (
document.querySelectorAll('input[data-slot-input]')
);
const submitBtn = /** @type {HTMLButtonElement} */ (document.getElementById('submit-btn'));
const bodyBtns = /** @type {NodeListOf<HTMLButtonElement>} */ (
document.querySelectorAll('[data-body]')
);
const styleBtns = /** @type {NodeListOf<HTMLButtonElement>} */ (
document.querySelectorAll('.style-card[data-type]')
);
// ── Camera support gating ──────────────────────────────────────────────────
if (!cameraSupported) {
heroCameraBtn?.setAttribute('disabled', '');
heroCameraBtn?.setAttribute('aria-disabled', 'true');
heroCameraBtn?.setAttribute('title', 'Camera not available in this browser');
unsupportedMsg?.classList.add('show');
}
// ── Top bar back ───────────────────────────────────────────────────────────
backBtn?.addEventListener('click', () => {
const active = document.querySelector('.step.active')?.getAttribute('data-step');
if (active === 'capture') window.location.assign('/create');
else if (active === 'building' || active === 'done') showStep('capture');
else window.location.assign('/');
});
// ── Hero slot: tap → contextual default (camera if supported, else upload)
heroSlot?.addEventListener('click', (e) => {
const target = /** @type {HTMLElement} */ (e.target);
if (target.closest('.retake-btn')) return;
if (state.files[REQUIRED_SLOT]) return;
openForSlot(REQUIRED_SLOT, cameraSupported ? 'camera' : 'upload');
});
heroSlot?.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
if (state.files[REQUIRED_SLOT]) return;
openForSlot(REQUIRED_SLOT, cameraSupported ? 'camera' : 'upload');
}
});
heroCameraBtn?.addEventListener('click', () => {
if (heroCameraBtn.hasAttribute('disabled')) return;
openForSlot(REQUIRED_SLOT, 'camera');
});
heroUploadBtn?.addEventListener('click', () => openForSlot(REQUIRED_SLOT, 'upload'));
// Hero drag/drop
heroSlot?.addEventListener('dragover', (e) => {
e.preventDefault();
heroSlot.classList.add('drag');
});
heroSlot?.addEventListener('dragleave', () => heroSlot.classList.remove('drag'));
heroSlot?.addEventListener('drop', (e) => {
e.preventDefault();
heroSlot.classList.remove('drag');
const file = e.dataTransfer?.files?.[0];
if (file && isImage(file)) setSlot(REQUIRED_SLOT, file);
});
// ── Side slots ─────────────────────────────────────────────────────────────
sideFrames.forEach((frame) => {
const slot = frame.getAttribute('data-slot');
if (!slot || slot === REQUIRED_SLOT) return;
const open = () => {
if (state.files[slot]) return;
openForSlot(slot, state.lastMethod || (cameraSupported ? 'camera' : 'upload'));
};
frame.addEventListener('click', open);
frame.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
open();
}
});
frame.addEventListener('dragover', (e) => {
e.preventDefault();
frame.classList.add('drag');
});
frame.addEventListener('dragleave', () => frame.classList.remove('drag'));
frame.addEventListener('drop', (e) => {
e.preventDefault();
frame.classList.remove('drag');
const file = e.dataTransfer?.files?.[0];
if (file && isImage(file)) setSlot(slot, file);
});
});
// ── File inputs ────────────────────────────────────────────────────────────
slotInputs.forEach((input) => {
input.addEventListener('change', () => {
const slot = input.getAttribute('data-slot-input');
const file = input.files?.[0];
if (slot && file && isImage(file)) setSlot(slot, file);
input.value = '';
});
});
// ── Selectors ──────────────────────────────────────────────────────────────
bodyBtns.forEach((btn) => {
btn.addEventListener('click', () => {
const val = /** @type {'male'|'female'} */ (btn.getAttribute('data-body'));
state.bodyType = val;
bodyBtns.forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));
});
});
styleBtns.forEach((btn) => {
btn.addEventListener('click', () => {
const val = /** @type {'v1'|'v2'} */ (btn.getAttribute('data-type'));
state.avatarType = val;
styleBtns.forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));
});
});
// ── External reset (e.g. "Try again" on the done step) ────────────────────
document.addEventListener('selfie:reset', () => {
ALL_SLOTS.forEach((s) => { state.files[s] = null; });
ALL_SLOTS.forEach(renderSlot);
updateSubmit();
});
// ── Submit ─────────────────────────────────────────────────────────────────
submitBtn.addEventListener('click', () => {
if (!state.files[REQUIRED_SLOT]) return;
document.dispatchEvent(
new CustomEvent('selfie:submit', {
detail: {
files: { ...state.files },
bodyType: state.bodyType,
avatarType: state.avatarType,
method: state.lastMethod || (cameraSupported ? 'camera' : 'upload'),
},
}),
);
submitBtn.innerHTML = '<span class="label">Sending…</span>';
submitBtn.disabled = true;
submitBtn.classList.remove('ready');
});
// ── Step machine ───────────────────────────────────────────────────────────
/** @param {'capture' | 'building' | 'done'} step */
function showStep(step) {
document.querySelectorAll('.step[data-step]').forEach((s) => {
s.classList.toggle('active', s.getAttribute('data-step') === step);
});
window.scrollTo({ top: 0, behavior: 'instant' in window ? 'instant' : 'auto' });
}
// ── Slot helpers ───────────────────────────────────────────────────────────
/** @param {File} file */
function isImage(file) {
return /^image\/(jpeg|png|webp|heic|heif)$/i.test(file.type || '');
}
/**
* @param {string} slot
* @param {'camera' | 'upload'} method
*/
function openForSlot(slot, method) {
state.lastMethod = method;
if (method === 'camera' && cameraSupported) {
openCamera(slot);
} else {
/** @type {HTMLInputElement | null} */ (
document.querySelector(`input[data-slot-input="${slot}"]`)
)?.click();
}
}
/**
* @param {string} slot
* @param {File} file
*/
function setSlot(slot, file) {
state.files[slot] = file;
renderSlot(slot);
updateSubmit();
// Let the page assess the freshly-added photo and warn early (before the
// minute-long build) if it's a drawing, blurry, or has no face.
document.dispatchEvent(new CustomEvent('selfie:photo-added', { detail: { slot, file } }));
}
/** @param {string} slot */
function clearSlot(slot) {
state.files[slot] = null;
renderSlot(slot);
updateSubmit();
}
/** @param {string} slot */
function renderSlot(slot) {
const isHero = slot === REQUIRED_SLOT;
const frame = /** @type {HTMLElement | null} */ (
document.querySelector(
isHero ? '.hero-slot[data-slot="frontal"]' : `.slot-frame[data-slot="${slot}"]`,
)
);
if (!frame) return;
const file = state.files[slot];
// Clear any previous error highlight; user has acted.
frame.classList.remove('error');
// Strip prior preview/retake artefacts.
frame.querySelector('img.preview')?.remove();
frame.querySelector('.retake-btn')?.remove();
if (!file) {
frame.classList.remove('filled');
// Hero: restore default icon/title/sub if they were hidden via inline style.
if (isHero) {
frame.querySelectorAll(':scope > .hero-icon, :scope > .hero-title, :scope > .hero-sub').forEach((el) => {
el.removeAttribute('style');
});
}
return;
}
frame.classList.add('filled');
// Hide hero defaults when filled.
if (isHero) {
frame.querySelectorAll(':scope > .hero-icon, :scope > .hero-title, :scope > .hero-sub').forEach((el) => {
/** @type {HTMLElement} */ (el).style.display = 'none';
});
}
const img = document.createElement('img');
img.className = 'preview';
img.alt = `${slot} photo preview`;
img.src = URL.createObjectURL(file);
img.onload = () => URL.revokeObjectURL(img.src);
frame.appendChild(img);
const retake = document.createElement('button');
retake.type = 'button';
retake.className = 'retake-btn';
retake.setAttribute('aria-label', `Remove ${slot} photo`);
retake.innerHTML =
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15A9 9 0 1 1 18.36 5.64L23 10"/></svg>';
retake.addEventListener('click', (e) => {
e.stopPropagation();
clearSlot(slot);
});
frame.appendChild(retake);
frame.addEventListener('keydown', (e) => {
if ((e.key === 'Delete' || e.key === 'Backspace') && state.files[slot]) {
e.preventDefault();
clearSlot(slot);
}
});
}
function updateSubmit() {
const hasRequired = !!state.files[REQUIRED_SLOT];
const extras = OPTIONAL_SLOTS.filter((k) => !!state.files[k]).length;
const labelEl = submitBtn.querySelector('.label');
const metaEl = submitBtn.querySelector('.meta');
if (!hasRequired) {
submitBtn.disabled = true;
submitBtn.classList.remove('ready');
if (labelEl) labelEl.textContent = 'Add a photo to start';
if (metaEl) metaEl.remove();
return;
}
const eta = extras === 0 ? ETA_FAST_SEC : ETA_HIGH_SEC;
const fidelityNote = extras === 0 ? '~' : extras === 1 ? '+1 angle · ~' : '+2 angles · ~';
const labelText = ALL_SLOTS.filter((k) => !!state.files[k]).length === 1
? 'Build my avatar'
: 'Build high-fidelity avatar';
submitBtn.disabled = false;
submitBtn.classList.add('ready');
if (labelEl) {
labelEl.textContent = labelText;
}
let meta = metaEl;
if (!meta) {
meta = document.createElement('span');
meta.className = 'meta';
submitBtn.appendChild(meta);
}
meta.textContent = `· ${fidelityNote}${eta}s`;
}
// ── Camera overlay ─────────────────────────────────────────────────────────
const camOverlay = document.getElementById('cam-overlay');
const camVideo = /** @type {HTMLVideoElement | null} */ (document.getElementById('cam-video'));
const camSlotName = document.getElementById('cam-slot-name');
const camError = document.getElementById('cam-error');
const camActionsLive = document.getElementById('cam-actions-live');
const camActionsReview = document.getElementById('cam-actions-review');
const camOval = document.getElementById('cam-oval');
const camHint = document.getElementById('cam-hint');
const camShutter = /** @type {HTMLButtonElement | null} */ (document.getElementById('cam-shutter'));
const camCountdown = document.getElementById('cam-countdown');
const camCountNum = document.getElementById('cam-count-num');
const cam = {
stream: /** @type {MediaStream | null} */ (null),
slot: /** @type {string | null} */ (null),
pendingFile: /** @type {File | null} */ (null),
pendingUrl: /** @type {string | null} */ (null),
qualitySession: /** @type {any} */ (null),
faceLocked: false,
countdownTimers: /** @type {number[]} */ ([]),
};
/** @param {string} slot */
async function openCamera(slot) {
if (!camOverlay || !camVideo) return;
cam.slot = slot;
cam.faceLocked = false;
if (camSlotName) camSlotName.textContent = slotPretty(slot);
if (camHint) {
camHint.textContent = slot === REQUIRED_SLOT
? 'Center your face in the oval'
: slot === 'left'
? 'Turn ~45° to your left'
: 'Turn ~45° to your right';
camHint.classList.remove('ok');
}
camOval?.classList.remove('detected');
setShutterEnabled(slot !== REQUIRED_SLOT);
setCamMode('live');
camError?.setAttribute('hidden', '');
camOverlay.classList.add('open');
try {
cam.stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 1706 } },
audio: false,
});
camVideo.srcObject = cam.stream;
} catch (err) {
log.warn('[selfie] camera error:', err);
const denied = err?.name === 'NotAllowedError' || err?.name === 'PermissionDeniedError';
const msg = denied
? 'Camera access was denied. Grant permission in your browser settings, or use Upload instead.'
: 'Could not access camera. Check permissions and try again, or use Upload.';
// Closing the overlay hides #cam-error the same frame, so the user would
// see "nothing happened". Surface the reason on the persistent page banner
// (next to the Upload affordance) instead, then close the overlay.
showPageNotice(msg);
closeCamera();
return;
}
startFaceQuality(slot);
}
async function startFaceQuality(slot) {
const meshOverlay = document.getElementById('cam-mesh-overlay');
const badges = document.getElementById('cam-badges');
if (!camVideo || !meshOverlay) {
setShutterEnabled(true);
return;
}
preload();
await new Promise((res) => {
if (camVideo.readyState >= 2) return res();
camVideo.addEventListener('loadeddata', res, { once: true });
});
try {
const slotKey = slot === REQUIRED_SLOT ? 'frontal' : slot;
cam.qualitySession = await createQualitySession(camVideo, meshOverlay, {
slot: slotKey,
onUpdate: (report) => {
renderQualityBadges(badges, report, slotKey);
updateCameraHints(report, slotKey);
},
});
cam.qualitySession.start();
camOval?.setAttribute('hidden', '');
} catch (err) {
log.warn('[selfie] face-quality init failed, falling back:', err);
setShutterEnabled(true);
}
}
function renderQualityBadges(container, report, slot) {
if (!container) return;
if (!report.faceFound) {
container.innerHTML = '<span class="cam-badge-chip bad">No face</span>';
return;
}
const slotCfg = SLOT_PRESETS[slot] || SLOT_PRESETS.frontal;
const chips = [
{ text: 'Face', ok: true },
{ text: `Yaw ${Math.round(report.yaw)}°`, ok: report.yawOk },
{ text: report.centered ? 'Centered' : 'Recenter', ok: report.centered },
{ text: report.blurOk ? 'Sharp' : 'Blurry', ok: report.blurOk },
];
const lumaLabel = report.luma < 40 ? 'Too dark' : report.luma > 218 ? 'Bright' : 'Lit';
chips.push({ text: lumaLabel, ok: report.lumaOk });
container.innerHTML = chips.map((c) =>
`<span class="cam-badge-chip ${c.ok ? 'ok' : 'bad'}">${c.text}</span>`
).join('');
}
function updateCameraHints(report, slot) {
if (!report.faceFound) {
setShutterEnabled(false);
camOval?.classList.remove('detected');
if (camHint) {
camHint.textContent = 'No face detected — face the camera';
camHint.classList.remove('ok');
}
return;
}
const allPass = report.allPass;
setShutterEnabled(true);
camOval?.classList.toggle('detected', allPass);
if (camHint) {
if (allPass) {
camHint.textContent = 'Looks good — tap the shutter';
camHint.classList.add('ok');
cam.faceLocked = true;
} else if (!report.yawOk) {
camHint.textContent = slot === 'frontal'
? 'Face the camera straight on'
: `Turn your head ${slot} (~45°)`;
camHint.classList.remove('ok');
} else if (!report.centered) {
camHint.textContent = 'Center your face in the oval';
camHint.classList.remove('ok');
} else if (!report.blurOk) {
camHint.textContent = 'Hold steady — image is blurry';
camHint.classList.remove('ok');
} else if (!report.lumaOk) {
camHint.textContent = report.luma < 40 ? 'Too dark — find better light' : 'Too bright — reduce glare';
camHint.classList.remove('ok');
} else {
camHint.textContent = 'Almost there...';
camHint.classList.remove('ok');
}
}
}
function stopFaceQuality() {
if (cam.qualitySession) {
cam.qualitySession.stop();
cam.qualitySession = null;
}
const meshOverlay = document.getElementById('cam-mesh-overlay');
if (meshOverlay) {
const ctx = meshOverlay.getContext('2d');
if (ctx) ctx.clearRect(0, 0, meshOverlay.width, meshOverlay.height);
}
const badges = document.getElementById('cam-badges');
if (badges) badges.innerHTML = '';
}
/** @param {boolean} on */
function setShutterEnabled(on) {
if (!camShutter) return;
if (on) camShutter.removeAttribute('disabled');
else camShutter.setAttribute('disabled', '');
}
function closeCamera() {
stopFaceQuality();
cancelCountdown();
if (cam.stream) {
cam.stream.getTracks().forEach((t) => t.stop());
cam.stream = null;
}
if (camVideo) camVideo.srcObject = null;
camOverlay?.classList.remove('open');
clearPending();
cam.slot = null;
cam.faceLocked = false;
}
function clearPending() {
if (cam.pendingUrl) URL.revokeObjectURL(cam.pendingUrl);
cam.pendingUrl = null;
cam.pendingFile = null;
document.querySelector('#cam-stage img.preview')?.remove();
}
/** @param {'live' | 'review'} mode */
function setCamMode(mode) {
if (mode === 'live') {
camActionsLive?.removeAttribute('hidden');
camActionsReview?.setAttribute('hidden', '');
// Re-show the oval while shooting.
camOval?.removeAttribute('hidden');
camHint?.removeAttribute('hidden');
} else {
camActionsLive?.setAttribute('hidden', '');
camActionsReview?.removeAttribute('hidden');
camOval?.setAttribute('hidden', '');
camHint?.setAttribute('hidden', '');
}
}
/** @param {string} msg */
function showCamError(msg) {
if (!camError) return;
camError.textContent = msg;
camError.removeAttribute('hidden');
}
// Surface an actionable notice on the persistent page banner (the same element
// used for unsupported browsers). Used when the camera can't open — its message
// must outlive the overlay being closed.
function showPageNotice(msg) {
if (!unsupportedMsg) return;
unsupportedMsg.textContent = msg;
unsupportedMsg.classList.add('show');
}
camOverlay?.addEventListener('click', (e) => {
const target = /** @type {HTMLElement} */ (e.target);
const action = target.closest('[data-cam-action]')?.getAttribute('data-cam-action');
if (!action) return;
if (action === 'cancel') closeCamera();
else if (action === 'shoot') startCountdown();
else if (action === 'retake') {
clearPending();
setCamMode('live');
startFaceQuality(cam.slot || REQUIRED_SLOT);
} else if (action === 'use') confirmCamShot();
});
// Escape closes the camera dialog (it's role="dialog" aria-modal) — keyboard
// parity with the Cancel button so the overlay is never a mouse-only trap.
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && camOverlay?.classList.contains('open')) {
e.preventDefault();
closeCamera();
}
});
function startCountdown() {
if (!camShutter || camShutter.hasAttribute('disabled')) return;
if (cam.countdownTimers.length) return;
setShutterEnabled(false);
camOval?.setAttribute('hidden', '');
camHint?.setAttribute('hidden', '');
const steps = ['3', '2', '1'];
camCountdown?.classList.add('show');
steps.forEach((s, i) => {
const t = window.setTimeout(() => {
if (camCountNum) {
camCountNum.textContent = s;
// retrigger animation by removing/adding
camCountNum.style.animation = 'none';
void camCountNum.offsetWidth;
camCountNum.style.animation = '';
}
}, i * 950);
cam.countdownTimers.push(t);
});
const fireT = window.setTimeout(() => {
camCountdown?.classList.remove('show');
shoot();
cam.countdownTimers = [];
}, steps.length * 950);
cam.countdownTimers.push(fireT);
}
function cancelCountdown() {
cam.countdownTimers.forEach((t) => clearTimeout(t));
cam.countdownTimers = [];
camCountdown?.classList.remove('show');
}
async function shoot() {
if (!camVideo || !cam.stream) return;
if (camShutter?.hasAttribute('disabled')) return;
const w = camVideo.videoWidth;
const h = camVideo.videoHeight;
if (!w || !h) return;
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) return;
// Un-mirror: the <video> is CSS-flipped for selfie feel, but the saved file
// should match what the camera actually sees.
ctx.drawImage(camVideo, 0, 0, w, h);
stopFaceQuality();
const blob = await new Promise((res) => canvas.toBlob(res, 'image/jpeg', 0.92));
if (!blob) {
showCamError('Snapshot failed. Try again.');
return;
}
const file = new File([blob], `${cam.slot || 'photo'}.jpg`, { type: 'image/jpeg' });
cam.pendingFile = file;
cam.pendingUrl = URL.createObjectURL(file);
const stage = document.getElementById('cam-stage');
if (stage) {
const img = document.createElement('img');
img.className = 'preview';
img.alt = 'captured preview';
img.src = cam.pendingUrl;
stage.appendChild(img);
}
setCamMode('review');
}
function confirmCamShot() {
if (!cam.pendingFile || !cam.slot) return;
const slot = cam.slot;
const file = cam.pendingFile;
cam.pendingFile = null;
cam.pendingUrl = null;
closeCamera();
setSlot(slot, file);
}
// ── Homepage handoff ─────────────────────────────────────────────────────────
// The homepage Avatar Studio teaser lets a visitor drop/capture a selfie, then
// sends them here to finish the real build. It stashes that photo in
// sessionStorage; pick it up as the frontal slot so they don't re-capture.
(function ingestHandoff() {
let raw;
try {
raw = sessionStorage.getItem('threews:selfie-handoff');
if (raw) sessionStorage.removeItem('threews:selfie-handoff');
} catch {
return; // storage blocked (private mode / cookies off)
}
if (!raw) return;
let parsed;
try {
parsed = JSON.parse(raw);
} catch {
return;
}
const dataUrl = parsed?.dataUrl;
if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/')) return;
const file = dataUrlToFile(dataUrl, typeof parsed?.name === 'string' ? parsed.name : 'selfie.jpg');
if (file) setSlot(REQUIRED_SLOT, file);
})();
/**
* @param {string} dataUrl
* @param {string} name
* @returns {File | null}
*/
function dataUrlToFile(dataUrl, name) {
const comma = dataUrl.indexOf(',');
if (comma < 0) return null;
const header = dataUrl.slice(0, comma);
const mime = (header.match(/^data:([^;]+)/) || [])[1] || 'image/jpeg';
const body = dataUrl.slice(comma + 1);
let bytes;
try {
const bin = /;base64/i.test(header) ? atob(body) : decodeURIComponent(body);
bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
} catch {
return null;
}
const ext = mime === 'image/png' ? 'png' : mime === 'image/webp' ? 'webp' : 'jpg';
const safeName = /\.[a-z0-9]+$/i.test(name) ? name : `${name}.${ext}`;
return new File([bytes], safeName, { type: mime });
}
// ── Utilities ──────────────────────────────────────────────────────────────
/** @param {string} slot */
function slotPretty(slot) {
if (slot === 'frontal') return 'selfie';
if (slot === 'left') return 'left angle';
if (slot === 'right') return 'right angle';
return slot;
}