Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

image-gen.tsx

296 lines11.0 KB

1import { useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { Download, Loader2, Send, X } from 'lucide-react'
4​
5interface GeneratedImage {
6 url?: string
7 b64Json?: string
8 revisedPrompt?: string
9}
10​
11interface ImageGenResult {
12 id: string
13 model: string
14 images: Array<GeneratedImage>
15 usage?: {
16 promptTokens?: number
17 completionTokens?: number
18 totalTokens?: number
19 }
21​
22const IMAGE_MODELS = [
23 { value: 'openai/gpt-5-image-mini', label: 'OpenAI GPT-5 Image Mini' },
24 { value: 'openai/gpt-5-image', label: 'OpenAI GPT-5 Image' },
25 {
26 value: 'google/gemini-nano-banana-2.1',
27 label: 'Nano Banana 2.1',
28 },
29 {
30 value: 'google/gemini-3-pro-image',
31 label: 'Gemini 3 Pro Image (Nano Banana Pro)',
32 },
33] as const
34​
35const IMAGE_SIZES = [
36 { value: '1024x1024', label: '1024x1024 (1:1)' },
37 { value: '1248x832', label: '1248x832 (3:2)' },
38 { value: '832x1248', label: '832x1248 (2:3)' },
39 { value: '1184x864', label: '1184x864 (4:3)' },
40 { value: '864x1184', label: '864x1184 (3:4)' },
41 { value: '1344x768', label: '1344x768 (16:9)' },
42 { value: '768x1344', label: '768x1344 (9:16)' },
43] as const
44​
45function ImageGenPage() {
46 const [prompt, setPrompt] = useState('')
47 const [model, setModel] = useState<string>(IMAGE_MODELS[0].value)
48 const [size, setSize] = useState<string>(IMAGE_SIZES[0].value)
49 const [isLoading, setIsLoading] = useState(false)
50 const [result, setResult] = useState<ImageGenResult | null>(null)
51 const [error, setError] = useState<string | null>(null)
52 const [history, setHistory] = useState<
53 Array<{ prompt: string; result: ImageGenResult }>
54 >([])
55​
56 async function handleGenerate() {
57 if (!prompt.trim() || isLoading) return
58​
59 setIsLoading(true)
60 setError(null)
61 setResult(null)
62​
63 try {
64 const res = await fetch('/api/image-gen', {
65 method: 'POST',
66 headers: { 'Content-Type': 'application/json' },
67 body: JSON.stringify({ prompt: prompt.trim(), model, size }),
68 })
69​
70 if (!res.ok) {
71 const errBody = await res.json().catch(() => null)
72 throw new Error(errBody?.error || `Request failed (${res.status})`)
73 }
74​
75 const data: ImageGenResult = await res.json()
76 setResult(data)
77 setHistory((prev) => [{ prompt: prompt.trim(), result: data }, ...prev])
78 } catch (err: any) {
79 setError(err.message || 'Something went wrong')
80 } finally {
81 setIsLoading(false)
82 }
83 }
84​
85 function getImageSrc(image: GeneratedImage): string | null {
86 if (image.url) return image.url
87 if (image.b64Json) return `data:image/png;base64,${image.b64Json}`
88 return null
89 }
90​
91 return (
92 <div className="flex flex-col h-[calc(100vh-72px)] bg-gray-900">
93 {/* Controls bar */}
94 <div className="border-b border-orange-500/20 bg-gray-800 px-4 py-3">
95 <div className="flex flex-wrap items-end gap-3">
96 <div className="flex-1 min-w-[200px]">
97 <label className="text-sm text-gray-400 mb-2 block">Model:</label>
98 <select
99 value={model}
100 onChange={(e) => setModel(e.target.value)}
101 disabled={isLoading}
102 className="w-full rounded-lg border border-orange-500/20 bg-gray-900 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-orange-500/50 disabled:opacity-50"
103 >
104 {IMAGE_MODELS.map((m) => (
105 <option key={m.value} value={m.value}>
106 {m.label}
107 </option>
108 ))}
109 </select>
110 </div>
111 <div className="min-w-[180px]">
112 <label className="text-sm text-gray-400 mb-2 block">Size:</label>
113 <select
114 value={size}
115 onChange={(e) => setSize(e.target.value)}
116 disabled={isLoading}
117 className="w-full rounded-lg border border-orange-500/20 bg-gray-900 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-orange-500/50 disabled:opacity-50"
118 >
119 {IMAGE_SIZES.map((s) => (
120 <option key={s.value} value={s.value}>
121 {s.label}
122 </option>
123 ))}
124 </select>
125 </div>
126 </div>
127 </div>
128​
129 {/* Main content area */}
130 <div className="flex-1 overflow-y-auto px-4 py-6">
131 {/* Current result */}
132 {result && result.images.length > 0 && (
133 <div className="mb-8">
134 <div className="text-sm text-gray-400 mb-3">
135 <span className="text-orange-400 font-medium">Prompt:</span>{' '}
136 {history[0]?.prompt}
137 {result.usage?.totalTokens != null && (
138 <span className="ml-3 text-gray-500">
139 ({result.usage.totalTokens} tokens)
140 </span>
141 )}
142 </div>
143 <div className="flex flex-wrap gap-4">
144 {result.images.map((image, i) => {
145 const src = getImageSrc(image)
146 if (!src) return null
147 return (
148 <div key={i} className="relative group">
149 <img
150 src={src}
151 alt={image.revisedPrompt || prompt}
152 className="max-w-full rounded-lg border border-gray-700 shadow-lg"
153 style={{ maxHeight: '512px' }}
154 />
155 {image.revisedPrompt && (
156 <div className="mt-2 text-xs text-gray-500 max-w-md">
157 <span className="text-gray-400">Revised:</span>{' '}
158 {image.revisedPrompt}
159 </div>
160 )}
161 <a
162 href={src}
163 download={`image-${Date.now()}-${i}.png`}
164 className="absolute top-2 right-2 p-2 bg-gray-900/80 hover:bg-gray-800 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity"
165 title="Download"
166 >
167 <Download className="w-4 h-4 text-white" />
168 </a>
169 </div>
170 )
171 })}
172 </div>
173 </div>
174 )}
175​
176 {/* Loading */}
177 {isLoading && (
178 <div className="flex flex-col items-center justify-center py-20 gap-4">
179 <Loader2 className="w-8 h-8 text-orange-500 animate-spin" />
180 <p className="text-gray-400 text-sm">Generating image...</p>
181 </div>
182 )}
183​
184 {/* Error */}
185 {error && (
186 <div className="mb-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
187 <div className="flex items-start gap-3">
188 <X className="w-5 h-5 text-red-400 shrink-0 mt-0.5" />
189 <div>
190 <p className="text-red-400 font-medium">Generation failed</p>
191 <p className="text-red-300/70 text-sm mt-1">{error}</p>
192 </div>
193 </div>
194 </div>
195 )}
196​
197 {/* Empty state */}
198 {!result && !isLoading && !error && (
199 <div className="flex flex-col items-center justify-center py-20 gap-3 text-gray-500">
200 <div className="w-16 h-16 rounded-2xl bg-gray-800 flex items-center justify-center">
201 <svg
202 className="w-8 h-8 text-gray-600"
203 fill="none"
204 viewBox="0 0 24 24"
205 stroke="currentColor"
206 >
207 <path
208 strokeLinecap="round"
209 strokeLinejoin="round"
210 strokeWidth={1.5}
211 d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909M3.75 21h16.5A2.25 2.25 0 0022.5 18.75V5.25A2.25 2.25 0 0020.25 3H3.75A2.25 2.25 0 001.5 5.25v13.5A2.25 2.25 0 003.75 21z"
212 />
213 </svg>
214 </div>
215 <p className="text-sm">Enter a prompt below to generate an image</p>
216 </div>
217 )}
218​
219 {/* History */}
220 {history.length > 1 && (
221 <div className="mt-8 border-t border-gray-800 pt-6">
222 <h3 className="text-sm font-medium text-gray-400 mb-4">
223 Previous Generations
224 </h3>
225 <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
226 {history.slice(1).map((entry, i) =>
227 entry.result.images.map((image, j) => {
228 const src = getImageSrc(image)
229 if (!src) return null
230 return (
231 <div
232 key={`${i}-${j}`}
233 className="rounded-lg border border-gray-800 overflow-hidden bg-gray-800/30"
234 >
235 <img
236 src={src}
237 alt={entry.prompt}
238 className="w-full object-cover"
239 style={{ maxHeight: '200px' }}
240 />
241 <div className="p-2 text-xs text-gray-500 truncate">
242 {entry.prompt}
243 </div>
244 </div>
245 )
246 }),
247 )}
248 </div>
249 </div>
250 )}
251 </div>
252​
253 {/* Input area */}
254 <div className="border-t border-orange-500/10 bg-gray-900/80 backdrop-blur-sm">
255 <div className="w-full px-4 py-3">
256 <div className="relative flex items-end gap-2">
257 <div className="flex-1 relative">
258 <textarea
259 value={prompt}
260 onChange={(e) => setPrompt(e.target.value)}
261 placeholder="Describe the image you want to generate..."
262 className="w-full rounded-lg border border-orange-500/20 bg-gray-800/50 pl-4 pr-12 py-3 text-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-orange-500/50 focus:border-transparent resize-none overflow-hidden shadow-lg"
263 rows={1}
264 style={{ minHeight: '44px', maxHeight: '200px' }}
265 disabled={isLoading}
266 onInput={(e) => {
267 const target = e.target as HTMLTextAreaElement
268 target.style.height = 'auto'
269 target.style.height =
270 Math.min(target.scrollHeight, 200) + 'px'
271 }}
272 onKeyDown={(e) => {
273 if (e.key === 'Enter' && !e.shiftKey && prompt.trim()) {
274 e.preventDefault()
275 handleGenerate()
276 }
277 }}
278 />
279 <button
280 onClick={handleGenerate}
281 disabled={!prompt.trim() || isLoading}
282 className="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-orange-500 hover:text-orange-400 disabled:text-gray-500 transition-colors focus:outline-none"
283 >
284 <Send className="w-4 h-4" />
285 </button>
286 </div>
287 </div>
288 </div>
289 </div>
290 </div>
291 )
293​
294export const Route = createFileRoute('/image-gen')({
295 component: ImageGenPage,
296})