Lumen & Gesso / website · lumengesso.com / app / studio / Studio.tsx
| 1 | 'use client'; |
| 2 | import { createPasskeyAccount } from '@/app/lib/auth-client'; |
| 3 | import { useEffect, useRef, useState } from 'react'; |
| 4 | import styles from './studio.module.css'; |
| 5 | import PrintPanel from './PrintPanel'; |
| 6 | |
| 7 | type Model = { id: string; label: string; available: boolean }; |
| 8 | type StudioStatus = { signedIn: boolean; ready: boolean; models: Model[]; feedbackAvailable?: boolean; signupAvailable?: boolean; maxUploadBytes: number; maxPixels: number }; |
| 9 | type Action = 'generate' | 'revise' | 'feedback'; |
| 10 | const INITIAL = { brightness: 100, contrast: 100, saturation: 100, rotate: 0 }; |
| 11 | const MAX_PIXELS = 20_000_000; |
| 12 | const MAX_FILE = 10_000_000; |
| 13 | const RATIOS = { original: 0, square: 1, portrait: 0.75, landscape: 4 / 3 }; |
| 14 | type Ratio = keyof typeof RATIOS; |
| 15 | |
| 16 | function loadImage(blob: Blob): Promise<HTMLImageElement> { |
| 17 | const path = URL.createObjectURL(blob); |
| 18 | return new Promise((resolve, reject) => { |
| 19 | const image = new Image(); |
| 20 | image.onload = () => { URL.revokeObjectURL(path); resolve(image); }; |
| 21 | image.onerror = () => { URL.revokeObjectURL(path); reject(new Error('That file could not be read as an image.')); }; |
| 22 | image.src = path; |
| 23 | }); |
| 24 | } |
| 25 | function exportBitmap(canvas: HTMLCanvasElement, type: string, quality?: number) { |
| 26 | return new Promise<Blob>((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error('Could not export this image.')), type, quality)); |
| 27 | } |
| 28 | |
| 29 | export default function Studio() { |
| 30 | const [status, setStatus] = useState<StudioStatus>(); |
| 31 | const [model, setModel] = useState(''); |
| 32 | const [mode, setMode] = useState<'edit' | 'ai' | 'print'>('edit'); |
| 33 | const [source, setSource] = useState<HTMLImageElement>(); |
| 34 | const [adjust, setAdjust] = useState(INITIAL); |
| 35 | const [ratio, setRatio] = useState<Ratio>('original'); |
| 36 | const [prompt, setPrompt] = useState(''); |
| 37 | const [feedback, setFeedback] = useState(''); |
| 38 | const [requestingLink, setRequestingLink] = useState(false); |
| 39 | const [message, setMessage] = useState(''); |
| 40 | const [busy, setBusy] = useState<Action | null>(null); |
| 41 | const [pixels, setPixels] = useState({ width: 0, height: 0 }); |
| 42 | const [prior, setPrior] = useState<HTMLImageElement>(); |
| 43 | const canvas = useRef<HTMLCanvasElement>(null); |
| 44 | const file = useRef<HTMLInputElement>(null); |
| 45 | |
| 46 | useEffect(() => { |
| 47 | const controller = new AbortController(); |
| 48 | fetch('/api/studio', { cache: 'no-store', signal: controller.signal }) |
| 49 | .then(r => { if (!r.ok) throw new Error(); return r.json() as Promise<StudioStatus>; }) |
| 50 | .then(data => { |
| 51 | setStatus(data); |
| 52 | setModel(data.models.find(item => item.available)?.id ?? ''); |
| 53 | }).catch(() => {}); |
| 54 | return () => controller.abort(); |
| 55 | }, []); |
| 56 | |
| 57 | useEffect(() => { |
| 58 | const output = canvas.current; |
| 59 | if (!source || !output) return; |
| 60 | const sideways = adjust.rotate % 180 !== 0; |
| 61 | const w = sideways ? source.naturalHeight : source.naturalWidth; |
| 62 | const h = sideways ? source.naturalWidth : source.naturalHeight; |
| 63 | const r = RATIOS[ratio] || w / h; |
| 64 | const cw = Math.min(w, h * r); |
| 65 | const ch = cw / r; |
| 66 | const scale = Math.min(1, 3200 / Math.max(cw, ch)); |
| 67 | output.width = Math.max(1, Math.floor(cw * scale)); |
| 68 | output.height = Math.max(1, Math.floor(ch * scale)); |
| 69 | const context = output.getContext('2d'); |
| 70 | if (!context) return; |
| 71 | context.save(); |
| 72 | context.translate(output.width / 2, output.height / 2); |
| 73 | context.rotate((adjust.rotate * Math.PI) / 180); |
| 74 | context.filter = `brightness(${adjust.brightness}%) contrast(${adjust.contrast}%) saturate(${adjust.saturation}%)`; |
| 75 | context.drawImage(source, -(source.naturalWidth * scale) / 2, -(source.naturalHeight * scale) / 2, source.naturalWidth * scale, source.naturalHeight * scale); |
| 76 | context.restore(); |
| 77 | setPixels({ width: output.width, height: output.height }); |
| 78 | }, [source, adjust, ratio]); |
| 79 | |
| 80 | function apply(next: HTMLImageElement, previous?: HTMLImageElement) { |
| 81 | setSource(next); setPrior(previous); setAdjust(INITIAL); setRatio('original'); setFeedback(''); |
| 82 | } |
| 83 | |
| 84 | async function upload(blob?: File) { |
| 85 | if (!blob || busy) return; |
| 86 | setMessage(''); |
| 87 | try { |
| 88 | if (!['image/jpeg', 'image/png', 'image/webp'].includes(blob.type)) throw new Error('Choose a JPEG, PNG, or WebP image.'); |
| 89 | if (blob.size > MAX_FILE) throw new Error('Choose an image under 10 MB.'); |
| 90 | const image = await loadImage(blob); |
| 91 | if (image.naturalWidth * image.naturalHeight > MAX_PIXELS) throw new Error('Choose an image under 20 megapixels.'); |
| 92 | apply(image); |
| 93 | } catch (error) { setMessage((error as Error).message); } |
| 94 | finally { if (file.current) file.current.value = ''; } |
| 95 | } |
| 96 | |
| 97 | async function download() { |
| 98 | if (!canvas.current || !source) return; |
| 99 | try { |
| 100 | const result = await exportBitmap(canvas.current, 'image/png'); |
| 101 | const url = URL.createObjectURL(result); |
| 102 | const link = document.createElement('a'); |
| 103 | link.href = url; link.download = 'lumen-and-gesso.png'; link.click(); |
| 104 | window.setTimeout(() => URL.revokeObjectURL(url), 1000); |
| 105 | } catch (error) { setMessage((error as Error).message); } |
| 106 | } |
| 107 | |
| 108 | async function emailLink() { |
| 109 | setRequestingLink(true); setMessage(''); |
| 110 | try { |
| 111 | const problem = await createPasskeyAccount(); |
| 112 | if (problem) setMessage(problem); else window.location.reload(); |
| 113 | } catch (error) { setMessage((error as Error).message); } |
| 114 | finally { setRequestingLink(false); } |
| 115 | } |
| 116 | |
| 117 | async function run(action: Action) { |
| 118 | if (busy || !status?.ready || !status.signedIn || (action !== 'feedback' && !model)) return; |
| 119 | setBusy(action); setMessage(''); |
| 120 | if (action === 'feedback') setFeedback(''); |
| 121 | try { |
| 122 | const form = new FormData(); |
| 123 | form.set('action', action); |
| 124 | if (action !== 'feedback') form.set('model', model); |
| 125 | form.set('prompt', prompt.trim()); |
| 126 | if (source && canvas.current) { |
| 127 | const rendered = await exportBitmap(canvas.current, 'image/jpeg', 0.90); |
| 128 | if (rendered.size > status.maxUploadBytes || pixels.width * pixels.height > status.maxPixels) { |
| 129 | throw new Error('This image is too large for the selected AI tools. Try cropping it first.'); |
| 130 | } |
| 131 | form.set('image', rendered, 'studio-reference.jpg'); |
| 132 | } |
| 133 | const response = await fetch('/api/studio', { method: 'POST', body: form }); |
| 134 | if (!response.ok) { |
| 135 | const failure = await response.json().catch(() => ({})) as { error?: string }; |
| 136 | throw new Error(failure.error || 'The model could not complete this request. Your image is unchanged.'); |
| 137 | } |
| 138 | if (action === 'feedback') { |
| 139 | const result = await response.json() as { feedback: string }; |
| 140 | setFeedback(result.feedback); |
| 141 | } else { |
| 142 | const current = await loadImage(await response.blob()); |
| 143 | apply(current, source); |
| 144 | setMessage('Image ready. Keep editing, ask for feedback, or download it.'); |
| 145 | } |
| 146 | } catch (error) { setMessage((error as Error).message); } |
| 147 | finally { setBusy(null); } |
| 148 | } |
| 149 | |
| 150 | return ( |
| 151 | <main className={styles.main}> |
| 152 | <div className={styles.intro}> |
| 153 | <p className={styles.eyebrow}>THE PORTRAIT STUDIO</p> |
| 154 | <h1>Make it yours.</h1> |
| 155 | <p>Upload a photo, edit it live, and download a clean image. No watermark added by Lumen & Gesso. No waiting for approval.</p> |
| 156 | </div> |
| 157 | <div className={styles.workbench}> |
| 158 | <section className={styles.preview} aria-label="Image preview"> |
| 159 | <div className={styles.previewBar}><span>Canvas</span><span>{source ? `${pixels.width} × ${pixels.height}` : 'No image yet'}</span></div> |
| 160 | <div className={styles.stage} onDragOver={e => e.preventDefault()} onDrop={e => { e.preventDefault(); void upload(e.dataTransfer.files[0]); }}> |
| 161 | {source ? <canvas ref={canvas} aria-label="Edited image preview" /> : <div className={styles.empty}><strong>Your picture goes here.</strong><p>Drop a photo or open one. JPEG, PNG or WebP.</p><button className="btn btn--rose btn--sm" type="button" onClick={() => file.current?.click()}>Upload an image</button></div>} |
| 162 | </div> |
| 163 | <input type="file" accept="image/jpeg,image/png,image/webp" ref={file} hidden onChange={e => void upload(e.target.files?.[0])} /> |
| 164 | <div className={styles.previewBar}> |
| 165 | <button type="button" className={styles.link} disabled={!!busy} onClick={() => file.current?.click()}>Open another image</button> |
| 166 | <button type="button" className="btn btn--rose btn--sm" disabled={!source || !!busy} onClick={() => void download()}>Download PNG</button> |
| 167 | </div> |
| 168 | </section> |
| 169 | <section className={styles.controls} aria-label="Studio controls"> |
| 170 | <div className={styles.switcher} aria-label="Tools"> |
| 171 | <button type="button" aria-pressed={mode === 'edit'} onClick={() => setMode('edit')}>Adjust</button> |
| 172 | <button type="button" aria-pressed={mode === 'ai'} onClick={() => setMode('ai')}>AI tools</button> |
| 173 | </div> |
| 174 | {mode === 'edit' ? ( |
| 175 | <> |
| 176 | <h2>Fine-tune the image</h2> |
| 177 | <p className={styles.hint}>Adjustments show instantly and stay in this browser. Save the PNG before closing the page.</p> |
| 178 | <fieldset disabled={!source || !!busy} className={styles.fields}> |
| 179 | {(['brightness', 'contrast', 'saturation'] as const).map(key => <label key={key} className={styles.slider}><span>{key} <output>{adjust[key]}%</output></span><input type="range" min="0" max="200" value={adjust[key]} onChange={e => setAdjust({ ...adjust, [key]: Number(e.target.value) })} /></label>)} |
| 180 | <label>Crop <select value={ratio} onChange={e => setRatio(e.target.value as Ratio)}><option value="original">Original</option><option value="square">Square</option><option value="portrait">Portrait</option><option value="landscape">Landscape</option></select></label> |
| 181 | <div className={styles.smallActions}><button type="button" onClick={() => setAdjust({ ...adjust, rotate: (adjust.rotate + 90) % 360 })}>Rotate 90°</button><button type="button" onClick={() => { setAdjust(INITIAL); setRatio('original'); }}>Reset</button>{prior && <button type="button" onClick={() => apply(prior, source)}>Swap with previous</button>}</div> |
| 182 | </fieldset> |
| 183 | </> |
| 184 | ) : mode === 'print' ? <PrintPanel canvas={canvas.current} hasImage={!!source} /> : ( |
| 185 | <> |
| 186 | <h2>Create, revise or get feedback</h2> |
| 187 | {!status?.ready ? <p className={styles.hint}>AI generation isn’t available right now. The upload, adjustment, and download tools still work for free.</p> : !status.signedIn ? <p className={styles.hint}><a href="/login?next=%2Fstudio">Sign in with your passkey</a> to use the AI tools. Save any edits before you leave this page.</p> : <p className={styles.hint}>Choose a model. If you submit a photo, it goes to the model to process your request.</p>} |
| 188 | {status?.signupAvailable && !status.signedIn && <button type="button" className="btn btn--rose btn--sm" disabled={requestingLink} onClick={() => void emailLink()}>{requestingLink ? 'Waiting for your device…' : 'New here? Create a passkey'}</button>} |
| 189 | <fieldset disabled={!!busy || !status?.ready || !status.signedIn} className={styles.fields}> |
| 190 | <label>Model<select value={model} onChange={e => setModel(e.target.value)}><option value="">Select a model</option>{status?.models.map(item => <option disabled={!item.available} value={item.id} key={item.id}>{item.label}</option>)}</select></label> |
| 191 | <label>{source ? 'What should change?' : 'Describe the image'}<textarea value={prompt} maxLength={1200} rows={4} placeholder="A charcoal portrait with a plain white background…" onChange={e => setPrompt(e.target.value)} /></label> |
| 192 | <button type="button" className="btn btn--rose btn--sm" disabled={!model || !prompt.trim()} onClick={() => void run(source ? 'revise' : 'generate')}>{source ? 'Revise image' : 'Generate image'}</button> |
| 193 | {source && status?.feedbackAvailable && <button type="button" className={styles.link} onClick={() => void run('feedback')}>Get visual feedback</button>} |
| 194 | </fieldset> |
| 195 | {busy && <p role="status">{busy === 'feedback' ? 'Reviewing the image…' : 'Working on your image…'}</p>} |
| 196 | {feedback && <p className={styles.feedback}>{feedback}</p>} |
| 197 | </> |
| 198 | )} |
| 199 | {message && <p className={styles.feedback} role="status">{message}</p>} |
| 200 | </section> |
| 201 | </div> |
| 202 | </main> |
| 203 | ); |
| 204 | } |