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

image-gen.tsx

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