Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
892 lines (807 loc) · 28.3 KB
/
Copy pathmain.js
File metadata and controls
892 lines (807 loc) · 28.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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
const $ = (id) => document.getElementById(id);
const STORAGE_KEY = 'portraitMixer.v3';
const OFFER_KEY = 'portraitMixer.exitOffer';
const OFFER_SEEN_KEY = 'portraitMixer.exitOfferSeen';
const MAX_FILE_BYTES = 15 * 1024 * 1024;
const state = {
person: null,
pet: null,
style: 'oil',
portraitId: null,
product: null,
config: null,
busy: false,
history: [], // earlier paintings, newest last, for "Go back"
previewImg: null, // decoded preview, used for the drawn fallback mockups
options: null, // colors/sizes per product from /api/options (Printful catalog)
colors: {}, // product -> chosen color name
mockups: {}, // "portraitId:variantId" -> [{url, title}] real Printful photos ([] = failed)
mockupPending: new Set(),
mockupIndex: {}, // "portraitId:variantId" -> which photo is shown
offer: false, // extra exit-popup discount accepted
leaving: false, // true while we send the user to Stripe
};
const money = (cents) => `$${(cents / 100).toFixed(2)}`;
const priceOf = (key) => {
const p = state.config.products[key];
return state.offer ? p.offerPrice : p.price;
};
const isPhysical = (key) => !!key && !!state.config?.products[key]?.physical;
function store(fn) {
try { return fn(); } catch { return null; }
}
// ---------- Alerts and busy state ----------
function showAlert(msg) {
$('alertBox').textContent = msg;
$('alertBox').hidden = false;
}
function hideAlert() {
$('alertBox').hidden = true;
}
function updateCreateButton() {
$('createBtn').disabled = state.busy || !(state.person && state.pet);
}
// ---------- Uploads ----------
function imageFromFile(file) {
return new Promise((resolve, reject) => {
if (!file || !file.type.startsWith('image/')) {
return reject(new Error('Please choose a photo.'));
}
if (file.size > MAX_FILE_BYTES) {
return reject(new Error('That photo is over 15 MB. Try a smaller one.'));
}
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => { URL.revokeObjectURL(url); resolve(img); };
img.onerror = () => { URL.revokeObjectURL(url); reject(new Error("Couldn't read that photo. Try a JPG or PNG.")); };
img.src = url;
});
}
function toJpegDataUrl(img, maxEdge = 1024, quality = 0.88) {
const scale = Math.min(1, maxEdge / Math.max(img.naturalWidth, img.naturalHeight));
const canvas = document.createElement('canvas');
canvas.width = Math.round(img.naturalWidth * scale);
canvas.height = Math.round(img.naturalHeight * scale);
canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL('image/jpeg', quality);
}
function bindUpload(kind) {
const input = $(`${kind}File`);
input.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file) return;
try {
const img = await imageFromFile(file);
state[kind] = toJpegDataUrl(img);
$(`${kind}Thumb`).src = state[kind];
$(`${kind}Thumb`).hidden = false;
$(`${kind}Empty`).hidden = true;
hideAlert();
} catch (err) {
showAlert(err.message);
} finally {
input.value = '';
updateCreateButton();
}
});
}
// ---------- Config (from /api/config) ----------
async function loadConfig() {
const res = await fetch('/api/config');
state.config = await res.json();
state.offer = !!state.config.exitOffer?.active && store(() => sessionStorage.getItem(OFFER_KEY)) === '1';
renderSale();
renderStyles();
renderPrices();
renderSizes();
renderReviews();
renderExamples();
renderTrustpilot();
}
function renderSale() {
const s = state.config.sale;
const parts = [];
if (s.active) parts.push(`${s.label}: ${s.percent}% off everything`);
if (state.offer) parts.push(`extra ${state.config.exitOffer.percent}% off applied`);
if (!parts.length) return;
$('saleBanner').textContent = `🎄 ${parts.join(' + ')} · Order now for Christmas`;
$('saleBanner').hidden = false;
}
function renderStyles() {
const grid = $('styleGrid');
grid.innerHTML = '';
for (const st of state.config.styles) {
const b = document.createElement('button');
b.type = 'button';
b.className = 'style-tile' + (st.key === state.style ? ' selected' : '');
b.innerHTML = `<span class="style-emoji">${st.emoji}</span><span></span>`;
b.lastChild.textContent = st.label;
b.addEventListener('click', () => { state.style = st.key; renderStyles(); });
grid.appendChild(b);
}
}
function renderPrices() {
for (const [key, p] of Object.entries(state.config.products)) {
const now = document.querySelector(`[data-price="${key}"]`);
if (now) now.textContent = money(priceOf(key));
const was = document.querySelector(`[data-was="${key}"]`);
if (was) was.textContent = state.config.sale.active || state.offer ? money(p.was) : '';
}
if (state.product) selectProduct(state.product);
}
function renderSizes() {
const sel = $('sizeSelect');
const keep = sel.value || 'M';
const color = currentColor('tshirt');
const sizes = color
? state.config.tshirtSizes.filter((s) => color.sizes[s])
: state.config.tshirtSizes;
sel.innerHTML = '';
for (const s of sizes) {
const o = document.createElement('option');
o.value = s;
o.textContent = s;
sel.appendChild(o);
}
sel.value = sizes.includes(keep) ? keep : (sizes.includes('M') ? 'M' : sizes[0]);
}
// Colors and sizes come from Printful's catalog. The page works without them
// (it falls back to the default product), so this loads in the background.
async function loadOptions() {
try {
const res = await fetch('/api/options');
if (!res.ok) throw new Error(`status ${res.status}`);
state.options = await res.json();
for (const [key, o] of Object.entries(state.options)) {
if (o?.colors?.length) state.colors[key] = o.default || o.colors[0].name;
}
} catch (err) {
console.warn('[options]', err.message);
}
// Mockups wait for this, so they are made for the right color the first time.
state.optionsDone = true;
renderSizes();
if (!$('result').hidden) {
renderProductThumbs();
startRealMockups();
if (state.product) selectProduct(state.product);
}
}
function currentColor(key) {
const o = state.options?.[key];
if (!o?.colors?.length) return null;
return o.colors.find((c) => c.name === state.colors[key]) || o.colors[0];
}
// The variant that is ordered (T-shirt depends on size).
function orderVariant(key) {
if (key === 'poster') return state.options?.poster?.variantId || null;
const c = currentColor(key);
if (!c) return null;
if (key === 'tshirt') return c.sizes[$('sizeSelect').value] || null;
return c.variantId;
}
// The variant used for photos (size doesn't change how a shirt looks, so always use M).
function photoVariant(key) {
if (key !== 'tshirt') return orderVariant(key);
const c = currentColor(key);
return c ? c.sizes.M || Object.values(c.sizes)[0] : null;
}
function renderColors(key) {
const o = state.options?.[key];
if (!isPhysical(key) || !o?.colors || o.colors.length < 2) {
$('colorRow').hidden = true;
return;
}
const chosen = currentColor(key);
$('colorName').textContent = chosen.name;
const box = $('swatches');
box.innerHTML = '';
for (const c of o.colors) {
const b = document.createElement('button');
b.type = 'button';
b.className = 'swatch' + (c.name === chosen.name ? ' selected' : '');
b.title = c.name;
b.setAttribute('aria-label', c.name);
const code = c.code || '#ccc';
// "White, Red inside" mugs show half white, half the inside color.
b.style.background = /inside/i.test(c.name) ? `linear-gradient(135deg, #fff 50%, ${code} 50%)` : code;
b.addEventListener('click', () => {
state.colors[key] = c.name;
renderColors(key);
if (key === 'tshirt') renderSizes();
renderMockupView(key);
renderProductThumbs();
});
box.appendChild(b);
}
$('colorRow').hidden = false;
}
function renderReviews() {
const list = state.config.reviews || [];
if (!list.length) return;
$('reviewList').innerHTML = '';
for (const r of list) {
const div = document.createElement('div');
div.className = 'review';
div.innerHTML =
(r.photo ? '<img class="review-photo" alt="" loading="lazy" />' : '') +
`<div><div class="stars">${'★'.repeat(r.stars || 5)}</div><p></p><div class="who"></div></div>`;
if (r.photo) div.querySelector('img').src = r.photo;
div.querySelector('p').textContent = `"${r.text}"`;
div.querySelector('.who').textContent = `- ${r.name}`;
$('reviewList').appendChild(div);
}
$('reviewsWrap').hidden = false;
}
function renderExamples() {
const list = state.config.examples || [];
if (!list.length) return;
const grid = $('exampleGrid');
grid.innerHTML = '';
for (const ex of list) {
const fig = document.createElement('figure');
fig.innerHTML = '<img alt="" loading="lazy" /><figcaption></figcaption>';
fig.querySelector('img').src = ex.src;
fig.querySelector('img').alt = ex.caption || 'Example painting';
fig.querySelector('figcaption').textContent = ex.caption || '';
grid.appendChild(fig);
}
$('examples').hidden = false;
}
function renderTrustpilot() {
const tp = state.config.trustpilot || {};
if (!tp.businessUnitId || !tp.templateId) return;
const box = $('trustpilotBox');
const w = document.createElement('div');
w.className = 'trustpilot-widget';
w.dataset.locale = 'en-US';
w.dataset.templateId = tp.templateId;
w.dataset.businessunitId = tp.businessUnitId;
w.dataset.styleHeight = '24px';
w.dataset.styleWidth = '100%';
const a = document.createElement('a');
a.href = tp.url || 'https://www.trustpilot.com';
a.target = '_blank';
a.rel = 'noopener';
a.textContent = 'Trustpilot';
w.appendChild(a);
box.appendChild(w);
box.hidden = false;
const s = document.createElement('script');
s.src = 'https://widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js';
s.async = true;
document.head.appendChild(s);
}
// ---------- Generate ----------
const WORKING_LINES = [
'Painting…',
'Mixing the colors…',
'Adding the finishing touches…',
'Almost ready…',
];
let workingTimer = null;
function startWorking() {
let i = 0;
$('working').hidden = false;
$('workingText').textContent = WORKING_LINES[0];
workingTimer = setInterval(() => {
i = (i + 1) % WORKING_LINES.length;
$('workingText').textContent = WORKING_LINES[i];
}, 4000);
}
function stopWorking() {
clearInterval(workingTimer);
$('working').hidden = true;
}
async function generate() {
if (state.busy) return;
state.busy = true;
updateCreateButton();
updateEditButton();
hideAlert();
// Retrying from under the painting: keep it on screen and show the spinner there.
const fromResult = !$('result').hidden;
if (fromResult) $('editWorking').hidden = false;
else startWorking();
try {
const res = await fetch('/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
personImage: state.person,
petImage: state.pet,
style: state.style,
}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
if (data.detail) console.error('[generate]', data.detail);
throw new Error(data.error || 'Something went wrong. Please try again.');
}
await setPortrait(data.id);
} catch (err) {
showAlert(err.message);
} finally {
stopWorking();
$('editWorking').hidden = true;
state.busy = false;
updateCreateButton();
updateEditButton();
}
}
// Remembers the previous painting so "Go back" works.
async function setPortrait(id) {
if (state.portraitId && state.portraitId !== id) state.history.push(state.portraitId);
state.portraitId = id;
store(() => localStorage.setItem(STORAGE_KEY, id));
await showPreview(id);
}
// ---------- Change / retry ----------
const EDIT_IDEAS = [
'Make us both smile',
'Make it brighter',
'Add a snowy Christmas background',
'Put us in a flower garden',
'Make my pet a bit bigger',
'Make it look more like a painting',
'Add a cozy fireplace behind us',
];
function renderChips() {
const box = $('chips');
box.innerHTML = '';
for (const idea of EDIT_IDEAS) {
const b = document.createElement('button');
b.type = 'button';
b.className = 'chip';
b.textContent = idea;
b.addEventListener('click', () => {
$('editInput').value = idea;
box.querySelectorAll('.chip').forEach((c) => c.classList.toggle('selected', c === b));
updateEditButton();
});
box.appendChild(b);
}
}
function updateEditButton() {
$('editBtn').disabled = state.busy || $('editInput').value.trim().length < 3;
$('retryBtn').disabled = state.busy;
$('backBtn').disabled = state.busy;
$('backBtn').hidden = !state.history.length;
}
async function runEdit() {
if (state.busy || !state.portraitId) return;
const edit = $('editInput').value.trim();
if (edit.length < 3) return;
state.busy = true;
updateEditButton();
updateCreateButton();
hideAlert();
$('editWorking').hidden = false;
try {
const res = await fetch('/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ baseId: state.portraitId, edit }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
if (data.detail) console.error('[generate]', data.detail);
throw new Error(data.error || 'Something went wrong. Please try again.');
}
$('editInput').value = '';
$('chips').querySelectorAll('.chip').forEach((c) => c.classList.remove('selected'));
await setPortrait(data.id);
} catch (err) {
showAlert(err.message);
$('alertBox').scrollIntoView({ behavior: 'smooth', block: 'center' });
} finally {
$('editWorking').hidden = true;
state.busy = false;
updateEditButton();
updateCreateButton();
}
}
function retry() {
if (state.busy) return;
if (!state.person || !state.pet) {
showAlert('Please choose your two photos again, then tap "Show my free preview".');
$('studio').scrollIntoView({ behavior: 'smooth', block: 'start' });
return;
}
generate();
}
async function goBack() {
if (state.busy || !state.history.length) return;
const prev = state.history.pop();
state.portraitId = prev;
store(() => localStorage.setItem(STORAGE_KEY, prev));
await showPreview(prev);
updateEditButton();
}
// ---------- Result ----------
// The preview is drawn on a canvas instead of an <img>, so there is no
// "Open image in new tab" / "Save image" on it. (It is the small watermarked copy anyway.)
async function showPreview(id) {
let img;
try {
const res = await fetch(`/api/image?id=${encodeURIComponent(id)}`);
if (!res.ok) throw new Error('gone');
const url = URL.createObjectURL(await res.blob());
img = await new Promise((resolve, reject) => {
const i = new Image();
i.onload = () => resolve(i);
i.onerror = reject;
i.src = url;
});
} catch {
store(() => localStorage.removeItem(STORAGE_KEY));
$('result').hidden = true;
showAlert('That painting is no longer available. Please create a new one.');
return;
}
state.previewImg = img;
const canvas = $('previewCanvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
canvas.getContext('2d').drawImage(img, 0, 0);
$('result').hidden = false;
$('thanks').hidden = true;
updateEditButton();
renderProductThumbs();
selectProduct(null);
$('result').scrollIntoView({ behavior: 'smooth', block: 'start' });
startRealMockups();
}
// ---------- Products and mockups ----------
const ORDER_TEXT = {
digital: 'Get my HD file',
poster: 'Order my poster',
mug: 'Order my mug',
tshirt: 'Order my T-shirt',
};
const PRODUCT_NAME = { poster: 'poster', mug: 'mug', tshirt: 'T-shirt' };
let warmedCheckout = false;
function selectProduct(key) {
state.product = key;
document.querySelectorAll('.product-card').forEach((c) => {
c.classList.toggle('selected', c.dataset.product === key);
});
$('sizeRow').hidden = key !== 'tshirt';
$('mockupWrap').hidden = !isPhysical(key);
renderColors(key);
$('orderBtn').hidden = !key;
if (key) {
$('orderBtn').disabled = false;
$('orderBtn').textContent = `${ORDER_TEXT[key]} · ${money(priceOf(key))}`;
}
if (isPhysical(key)) renderMockupView(key);
// Wake up the checkout function now so it is ready when they tap Order.
if (key && !warmedCheckout) {
warmedCheckout = true;
fetch('/api/checkout', { method: 'GET' }).catch(() => {});
}
}
const mockupKey = (key) => `${state.portraitId}:${photoVariant(key) || `default-${key}`}`;
function mockupSrc(key) {
const k = mockupKey(key);
const imgs = state.mockups[k];
if (imgs?.length) return imgs[state.mockupIndex[k] || 0].url;
return drawnMockup(key, currentColor(key)?.code);
}
function renderMockupView(key) {
const k = mockupKey(key);
const imgs = state.mockups[k];
$('mockupImg').src = mockupSrc(key);
const gallery = $('mockupGallery');
gallery.innerHTML = '';
if (imgs?.length > 1) {
imgs.forEach((m, i) => {
const b = document.createElement('button');
b.type = 'button';
b.className = (state.mockupIndex[k] || 0) === i ? 'selected' : '';
b.setAttribute('aria-label', m.title || `Photo ${i + 1}`);
b.innerHTML = '<img alt="" />';
b.firstChild.src = m.url;
b.addEventListener('click', () => {
state.mockupIndex[k] = i;
renderMockupView(key);
});
gallery.appendChild(b);
});
}
const name = PRODUCT_NAME[key];
if (imgs?.length) {
$('mockupNote').textContent = `This is how your ${name} will look.${imgs.length > 1 ? ' Tap the small pictures to see more.' : ''} Shipping is added at checkout.`;
} else if (imgs) {
$('mockupNote').textContent = 'Preview only. Shipping is added at checkout.';
} else {
$('mockupNote').textContent = `Getting real photos of your ${name}… Shipping is added at checkout.`;
requestMockup(key);
}
}
function renderProductThumbs() {
document.querySelectorAll('.product-card').forEach((c) => {
const key = c.dataset.product;
const thumb = c.querySelector('.pc-thumb');
if (!thumb) return;
thumb.src = key === 'digital' ? $('previewCanvas').toDataURL('image/jpeg', 0.7) : mockupSrc(key);
});
}
function startRealMockups() {
Object.keys(state.config.products).filter(isPhysical).forEach(requestMockup);
}
// Real product photos from Printful. They take 10-60 seconds, so the drawn
// preview shows first and is swapped out when the real ones arrive.
async function requestMockup(key) {
if (!state.portraitId || !state.optionsDone) return;
const k = mockupKey(key);
if (state.mockups[k] || state.mockupPending.has(k)) return;
state.mockupPending.add(k);
const refresh = () => {
renderProductThumbs();
if (state.product === key && mockupKey(key) === k) renderMockupView(key);
};
try {
const res = await fetch('/api/mockup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ portraitId: state.portraitId, product: key, variantId: photoVariant(key) }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok || !data.task) throw new Error(data.detail || data.error || 'no task');
const deadline = Date.now() + 120_000;
while (Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 4000));
const st = await fetch(`/api/mockup?task=${encodeURIComponent(data.task)}`).then((r) => r.json());
if (st.status === 'completed' && st.images?.length) {
state.mockups[k] = st.images;
refresh();
return;
}
if (st.status === 'failed') throw new Error(st.error || 'failed');
}
throw new Error('timed out');
} catch (err) {
console.warn(`[mockup] ${key}:`, err.message);
state.mockups[k] = [];
refresh();
} finally {
state.mockupPending.delete(k);
}
}
// Simple drawn mockups, used until the real Printful photo is ready.
function coverDraw(ctx, img, x, y, w, h) {
const scale = Math.max(w / img.naturalWidth, h / img.naturalHeight);
const dw = img.naturalWidth * scale;
const dh = img.naturalHeight * scale;
ctx.drawImage(img, x + (w - dw) / 2, y + (h - dh) / 2, dw, dh);
}
function roundRectPath(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function shirtPath(ctx) {
ctx.beginPath();
ctx.moveTo(240, 110);
ctx.quadraticCurveTo(300, 160, 360, 110);
ctx.lineTo(470, 170);
ctx.lineTo(430, 260);
ctx.lineTo(390, 240);
ctx.lineTo(390, 480);
ctx.lineTo(210, 480);
ctx.lineTo(210, 240);
ctx.lineTo(170, 260);
ctx.lineTo(130, 170);
ctx.closePath();
}
function drawnMockup(kind, color) {
const img = state.previewImg;
const canvas = document.createElement('canvas');
canvas.width = 600;
canvas.height = 600;
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#f4efe7';
ctx.fillRect(0, 0, 600, 600);
if (!img) return canvas.toDataURL('image/jpeg', 0.8);
if (kind === 'poster') {
ctx.fillStyle = '#ece4d6';
ctx.fillRect(0, 0, 600, 600);
ctx.fillStyle = 'rgba(0,0,0,0.18)';
ctx.fillRect(158, 78, 300, 400);
ctx.fillStyle = '#2b2118';
ctx.fillRect(150, 70, 300, 400);
ctx.fillStyle = '#ffffff';
ctx.fillRect(166, 86, 268, 368);
ctx.save();
ctx.beginPath();
ctx.rect(186, 106, 228, 328);
ctx.clip();
coverDraw(ctx, img, 186, 106, 228, 328);
ctx.restore();
ctx.fillStyle = '#d9cdb8';
ctx.fillRect(0, 540, 600, 60);
} else if (kind === 'mug') {
ctx.lineWidth = 34;
ctx.strokeStyle = '#e9e4dc';
ctx.beginPath();
ctx.arc(420, 300, 70, -Math.PI / 2, Math.PI / 2);
ctx.stroke();
roundRectPath(ctx, 130, 140, 300, 330, 28);
ctx.fillStyle = /^black$/i.test(state.colors.mug || '') ? '#1a1a1a' : '#ffffff';
ctx.fill();
ctx.save();
roundRectPath(ctx, 160, 190, 240, 230, 16);
ctx.clip();
coverDraw(ctx, img, 160, 190, 240, 230);
ctx.restore();
const g = ctx.createLinearGradient(130, 0, 430, 0);
g.addColorStop(0, 'rgba(0,0,0,0.18)');
g.addColorStop(0.35, 'rgba(0,0,0,0)');
g.addColorStop(0.75, 'rgba(0,0,0,0)');
g.addColorStop(1, 'rgba(0,0,0,0.22)');
roundRectPath(ctx, 130, 140, 300, 330, 28);
ctx.fillStyle = g;
ctx.fill();
} else if (kind === 'tshirt') {
shirtPath(ctx);
ctx.fillStyle = color || '#1f1f1f';
ctx.fill();
ctx.strokeStyle = 'rgba(0,0,0,0.15)';
ctx.lineWidth = 3;
ctx.stroke();
ctx.save();
ctx.beginPath();
ctx.rect(230, 190, 140, 160);
ctx.clip();
coverDraw(ctx, img, 230, 190, 140, 160);
ctx.restore();
}
return canvas.toDataURL('image/jpeg', 0.85);
}
// ---------- Checkout ----------
async function order() {
const btn = $('orderBtn');
btn.disabled = true;
btn.innerHTML = '<span class="btn-spinner" aria-hidden="true"></span> Opening secure checkout…';
hideAlert();
try {
const res = await fetch('/api/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
portraitId: state.portraitId,
product: state.product,
size: $('sizeSelect').value,
color: currentColor(state.product)?.name || '',
exitOffer: state.offer,
}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok || !data.url) throw new Error(data.error || 'Could not start checkout.');
state.leaving = true;
window.location.href = data.url;
} catch (err) {
showAlert(err.message);
selectProduct(state.product);
}
}
// ---------- "Before you go" offer ----------
function offerAvailable() {
return state.config?.exitOffer?.active && !state.offer &&
store(() => sessionStorage.getItem(OFFER_SEEN_KEY)) !== '1';
}
function showOffer() {
if (!offerAvailable() || !$('thanks').hidden) return;
store(() => sessionStorage.setItem(OFFER_SEEN_KEY, '1'));
const pct = state.config.exitOffer.percent;
$('offerTitle').textContent = `Wait! Take an extra ${pct}% off`;
$('offerText').textContent = state.portraitId
? `Your painting is ready. Get an extra ${pct}% off any print or download today, on top of the sale price.`
: `Your preview is free. Make your painting now and get an extra ${pct}% off on top of the sale price.`;
$('offerYes').textContent = `Yes, give me ${pct}% off`;
$('offerModal').hidden = false;
$('offerYes').focus();
}
function acceptOffer() {
state.offer = true;
store(() => sessionStorage.setItem(OFFER_KEY, '1'));
$('offerModal').hidden = true;
renderSale();
renderPrices();
const target = state.portraitId && !$('result').hidden ? 'result' : 'studio';
$(target).scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function bindOffer() {
$('offerYes').addEventListener('click', acceptOffer);
$('offerNo').addEventListener('click', () => { $('offerModal').hidden = true; });
$('offerModal').addEventListener('click', (e) => {
if (e.target === $('offerModal')) $('offerModal').hidden = true;
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') $('offerModal').hidden = true;
});
// Desktop: mouse heads for the tab bar / close button.
document.addEventListener('mouseout', (e) => {
if (!e.relatedTarget && e.clientY <= 0) showOffer();
});
// Phones: they switched away and came back.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && !state.leaving) setTimeout(showOffer, 600);
});
// If they have an unpaid painting, the browser asks "Leave site?" before closing.
window.addEventListener('beforeunload', (e) => {
if (state.leaving || !state.portraitId || $('result').hidden) return;
e.preventDefault();
e.returnValue = '';
});
}
// ---------- After payment ----------
function showThanks(portraitId, sessionId, product) {
$('result').hidden = true;
$('thanks').hidden = false;
if (product === 'digital') {
$('thanksTitle').textContent = 'Thank you! Your HD painting is ready.';
$('thanksText').textContent = 'Tap the button to save the full-size file. We also emailed it to you, so you can download it again any time.';
const link = $('downloadBtn');
link.href = `/api/download?id=${encodeURIComponent(portraitId)}&session_id=${encodeURIComponent(sessionId)}&dl=1`;
link.hidden = false;
} else {
$('thanksTitle').textContent = 'Thank you! Your order is in.';
$('thanksText').textContent = 'We are printing it now. We will email you when it ships.';
$('downloadBtn').hidden = true;
}
$('thanks').scrollIntoView({ behavior: 'smooth', block: 'start' });
}
// ---------- Init ----------
async function init() {
bindUpload('person');
bindUpload('pet');
$('createBtn').addEventListener('click', generate);
$('orderBtn').addEventListener('click', order);
renderChips();
$('editInput').addEventListener('input', updateEditButton);
$('editInput').addEventListener('keydown', (e) => { if (e.key === 'Enter') runEdit(); });
$('editBtn').addEventListener('click', runEdit);
$('retryBtn').addEventListener('click', retry);
$('backBtn').addEventListener('click', goBack);
document.querySelectorAll('.product-card').forEach((c) => {
c.addEventListener('click', () => selectProduct(c.dataset.product));
});
// No right-click / long-press save on the preview and mockups.
document.querySelectorAll('.protect').forEach((el) => {
el.addEventListener('contextmenu', (e) => e.preventDefault());
el.addEventListener('dragstart', (e) => e.preventDefault());
});
try {
await loadConfig();
} catch {
showAlert('Could not load the page settings. Please refresh.');
}
bindOffer();
updateCreateButton();
loadOptions();
const params = new URLSearchParams(window.location.search);
const paidId = params.get('paid');
const sessionId = params.get('session_id');
if (paidId && sessionId) {
state.portraitId = paidId;
showThanks(paidId, sessionId, params.get('product'));
history.replaceState(null, '', '/');
return;
}
if (params.get('cancelled')) {
showAlert('Checkout was cancelled. Your painting is still here.');
history.replaceState(null, '', '/');
}
const saved = store(() => localStorage.getItem(STORAGE_KEY));
if (saved) {
state.portraitId = saved;
showPreview(saved);
}
}
document.addEventListener('DOMContentLoaded', init);