()
| 11 | } |
| 12 | |
| 13 | function ImagePage() { |
| 14 | const [prompt, setPrompt] = useState( |
| 15 | 'A cute baby sea otter wearing a beret and glasses, sitting at a small cafe table, sipping a cappuccino', |
| 16 | ) |
| 17 | const [size, setSize] = useState('1024x1024') |
| 18 | const [numberOfImages, setNumberOfImages] = useState(1) |
| 19 | const [images, setImages] = useState<Array<GeneratedImage>>([]) |
| 20 | const [isLoading, setIsLoading] = useState(false) |
| 21 | const [error, setError] = useState<string | null>(null) |
| 22 | |
| 23 | const handleGenerate = async () => { |
| 24 | setIsLoading(true) |
| 25 | setError(null) |
| 26 | setImages([]) |
| 27 | |
| 28 | try { |
| 29 | const response = await fetch('/demo/api/ai/image', { |
| 30 | method: 'POST', |
| 31 | headers: { 'Content-Type': 'application/json' }, |
| 32 | body: JSON.stringify({ prompt, size, numberOfImages }), |
| 33 | }) |
| 34 | |
| 35 | const data = await response.json() |
| 36 | |
| 37 | if (!response.ok) { |
| 38 | throw new Error(data.error || 'Failed to generate image') |
| 39 | } |
| 40 | |
| 41 | setImages(data.images) |
| 42 | } catch (err: any) { |
| 43 | setError(err.message) |
| 44 | } finally { |
| 45 | setIsLoading(false) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | const getImageSrc = (image: GeneratedImage) => { |
| 50 | if (image.url) return image.url |
| 51 | if (image.b64Json) return `data:image/png;base64,${image.b64Json}` |
| 52 | return '' |
| 53 | } |
| 54 | |
| 55 | const handleDownload = async (image: GeneratedImage, index: number) => { |
| 56 | const src = getImageSrc(image) |
| 57 | if (!src) return |
| 58 | |
| 59 | try { |
| 60 | const response = await fetch(src) |
| 61 | const blob = await response.blob() |
| 62 | const url = URL.createObjectURL(blob) |
| 63 | const a = document.createElement('a') |
| 64 | a.href = url |
| 65 | a.download = `generated-image-${index + 1}.png` |
| 66 | document.body.appendChild(a) |
| 67 | a.click() |
| 68 | document.body.removeChild(a) |
| 69 | URL.revokeObjectURL(url) |
| 70 | } catch (err) { |
nothing calls this directly
no test coverage detected