Lumen & Gesso / website · lumengesso.com / app / studio / PrintPanel.tsx
| 1 | 'use client'; |
| 2 | |
| 3 | import { createPasskeyAccount } from '@/app/lib/auth-client'; |
| 4 | import { useEffect, useRef, useState } from 'react'; |
| 5 | import styles from './studio.module.css'; |
| 6 | |
| 7 | type Selection = { productId: string; size: string; orientation: 'portrait' | 'landscape'; frame: string; matteId?: string; wrap?: string }; |
| 8 | type PrintQuote = { |
| 9 | quoteToken: string; amountCents: number; currency: 'USD'; selection: Selection; |
| 10 | width: number; height: number; artworkSha256: string; expiresAt: string | number; |
| 11 | }; |
| 12 | type Access = { enabled: boolean; signedIn: boolean; signupAvailable?: boolean }; |
| 13 | const SELECTION: Selection = { productId: 'classic', size: '8x8', orientation: 'portrait', frame: 'black', matteId: 'nomat' }; |
| 14 | |
| 15 | export default function PrintPanel({ canvas, hasImage }: { canvas: HTMLCanvasElement | null; hasImage: boolean }) { |
| 16 | const [access, setAccess] = useState<Access>(); |
| 17 | const [image, setImage] = useState<Blob>(); |
| 18 | const [preview, setPreview] = useState(''); |
| 19 | const [quote, setQuote] = useState<PrintQuote>(); |
| 20 | const [approval, setApproval] = useState(false); |
| 21 | const [terms, setTerms] = useState(false); |
| 22 | const [busy, setBusy] = useState(false); |
| 23 | const [error, setError] = useState(''); |
| 24 | const [notice, setNotice] = useState(''); |
| 25 | const processing = useRef(false); |
| 26 | |
| 27 | useEffect(() => { |
| 28 | const c = new AbortController(); |
| 29 | fetch('/api/studio/print/quote', { cache: 'no-store', signal: c.signal }) |
| 30 | .then(r => r.ok ? r.json() as Promise<Access> : undefined) |
| 31 | .then(info => { if (!c.signal.aborted) setAccess(info ?? { enabled: false, signedIn: false }); }) |
| 32 | .catch(() => { if (!c.signal.aborted) setAccess({ enabled: false, signedIn: false }); }); |
| 33 | return () => c.abort(); |
| 34 | }, []); |
| 35 | |
| 36 | useEffect(() => { |
| 37 | if (!image) { setPreview(''); return; } |
| 38 | const url = URL.createObjectURL(image); |
| 39 | setPreview(url); |
| 40 | return () => URL.revokeObjectURL(url); |
| 41 | }, [image]); |
| 42 | |
| 43 | function snapshot() { |
| 44 | if (!canvas || !hasImage) throw new Error('Upload or create an image first.'); |
| 45 | if (canvas.width !== canvas.height) throw new Error('Choose Square under Adjust, then return here to review the 8 × 8 print.'); |
| 46 | // Freeze the pixels before any asynchronous work. A new proof always clears consent. |
| 47 | const rendition = document.createElement('canvas'); |
| 48 | rendition.width = canvas.width; rendition.height = canvas.height; |
| 49 | const context = rendition.getContext('2d'); |
| 50 | if (!context) throw new Error('Could not preview this print.'); |
| 51 | context.fillStyle = '#ffffff'; |
| 52 | context.fillRect(0, 0, rendition.width, rendition.height); |
| 53 | context.drawImage(canvas, 0, 0); |
| 54 | return new Promise<Blob>((resolve, reject) => rendition.toBlob(blob => blob ? resolve(blob) : reject(new Error('Could not encode this print.')), 'image/jpeg', .95)); |
| 55 | } |
| 56 | |
| 57 | async function prepare() { |
| 58 | if (processing.current) return; |
| 59 | processing.current = true; |
| 60 | setBusy(true); setError(''); setQuote(undefined); setImage(undefined); setApproval(false); setTerms(false); |
| 61 | try { |
| 62 | const exact = await snapshot(); |
| 63 | const form = new FormData(); |
| 64 | form.set('image', exact, 'approved-artwork.jpg'); |
| 65 | form.set('selection', JSON.stringify(SELECTION)); |
| 66 | const reply = await fetch('/api/studio/print/quote', { method: 'POST', body: form }); |
| 67 | const data = await reply.json() as PrintQuote & { error?: string }; |
| 68 | if (!reply.ok) throw new Error(data.error || 'Could not prepare a print quote.'); |
| 69 | setImage(exact); setQuote(data); |
| 70 | } catch (cause) { setError((cause as Error).message); } |
| 71 | finally { setBusy(false); processing.current = false; } |
| 72 | } |
| 73 | |
| 74 | async function requestSignIn() { |
| 75 | if (processing.current) return; |
| 76 | processing.current = true; setBusy(true); setError(''); setNotice(''); |
| 77 | try { |
| 78 | const problem = await createPasskeyAccount(); |
| 79 | if (problem) setNotice(problem); else window.location.reload(); |
| 80 | } catch (cause) { setError((cause as Error).message); } |
| 81 | finally { setBusy(false); processing.current = false; } |
| 82 | } |
| 83 | |
| 84 | async function checkout() { |
| 85 | if (!image || !quote || !approval || !terms || processing.current) return; |
| 86 | const expiry = typeof quote.expiresAt === 'number' ? quote.expiresAt : Date.parse(quote.expiresAt); |
| 87 | if (expiry <= Date.now()) { |
| 88 | setError('The quote expired. Review the current canvas and request a new price.'); |
| 89 | setQuote(undefined); setApproval(false); setTerms(false); |
| 90 | return; |
| 91 | } |
| 92 | processing.current = true; |
| 93 | setBusy(true); setError(''); |
| 94 | try { |
| 95 | const form = new FormData(); |
| 96 | form.set('image', image, 'approved-artwork.jpg'); |
| 97 | form.set('quoteToken', quote.quoteToken); |
| 98 | form.set('approved', 'true'); |
| 99 | form.set('termsAccepted', 'true'); |
| 100 | const reply = await fetch('/api/studio/print/checkout', { method: 'POST', body: form }); |
| 101 | const data = await reply.json() as { url?: string; error?: string }; |
| 102 | if (!reply.ok || !data.url) throw new Error(data.error || 'Could not open checkout.'); |
| 103 | const destination = new URL(data.url); |
| 104 | if (destination.origin !== 'https://checkout.stripe.com') throw new Error('Checkout returned an unexpected address.'); |
| 105 | window.location.assign(destination.href); |
| 106 | } catch (cause) { setError((cause as Error).message); } |
| 107 | finally { setBusy(false); processing.current = false; } |
| 108 | } |
| 109 | |
| 110 | return <section aria-label="Print approval"> |
| 111 | <h2>Approve your own print</h2> |
| 112 | <p className={styles.hint}>Digital downloads are still free. Review the exact artwork and price. The printer receives the approved file only after successful payment.</p> |
| 113 | {!access ? <p role="status">Checking print availability…</p> : !access.enabled ? <p>Physical print checkout is not open yet.</p> : !access.signedIn ? <div> |
| 114 | <p><a href="/login?next=%2Fstudio">Sign in with your passkey</a> for print checkout. Save your edits first.</p> |
| 115 | {access.signupAvailable && <button type="button" className="btn btn--rose btn--sm" disabled={busy} onClick={() => void requestSignIn()}>New here? Create a passkey</button>} |
| 116 | </div> : <> |
| 117 | <p>Classic matte-black frame · 8 × 8 in · no mat</p> |
| 118 | <button type="button" className="btn btn--rose btn--sm" disabled={busy || !hasImage} onClick={() => void prepare()}>{quote ? 'Review current canvas again' : 'Preview print and price'}</button> |
| 119 | {preview && quote && <div className={styles.fields}> |
| 120 | {/* eslint-disable-next-line @next/next/no-img-element */} |
| 121 | <img className={styles.printProof} src={preview} alt="Exact image to be sent to the printer" /> |
| 122 | <p><strong>{new Intl.NumberFormat('en-US', { style: 'currency', currency: quote.currency }).format(quote.amountCents / 100)}</strong> before tax · {quote.width} × {quote.height} px</p> |
| 123 | <label className={styles.check}><input type="checkbox" checked={approval} disabled={busy} onChange={e => setApproval(e.target.checked)} /> I approve this exact image and print selection.</label> |
| 124 | <label className={styles.check}><input type="checkbox" checked={terms} disabled={busy} onChange={e => setTerms(e.target.checked)} /> <span>I accept the <a href="/terms" target="_blank" rel="noreferrer">print terms</a> and <a href="/refund-policy" target="_blank" rel="noreferrer">refund policy</a>.</span></label> |
| 125 | <button type="button" className="btn btn--rose btn--sm" disabled={!approval || !terms || busy} onClick={() => void checkout()}>Continue to payment</button> |
| 126 | </div>} |
| 127 | </>} |
| 128 | {notice && <p role="status">{notice}</p>} |
| 129 | {busy && <p role="status">Working…</p>} |
| 130 | {error && <p className={styles.feedback} role="alert">{error}</p>} |
| 131 | </section>; |
| 132 | } |