Open History to see the last commit
1import { useCallback, useEffect, useRef, useState } from 'react'
2import { ImageIcon, Loader2, Plus, Shuffle, X } from 'lucide-react'
3import { useGenerateImage } from '@tanstack/ai-react'
4import type { MediaPrompt } from '@tanstack/ai/client'
5
6import { generateImageFn } from '@/lib/server-functions'
7import { byok, callWithByok, toByokProvider } from '@/lib/byok'
8import { getRandomImagePrompt } from '@/lib/prompts'
9import { IMAGE_MODELS } from '@/lib/models'
10import type { ImageModel } from '@/lib/models'
11import { readMediaFile, toImagePart } from '@/lib/media'
12import type { AttachedMedia } from '@/lib/media'
13
14interface ImageGeneratorProps {
15 onImageGenerated?: (imageUrl: string) => void
16}
17
18/** How the parent asks one card to run: the built prompt, nothing else. */
19type ImageRunner = (prompt: MediaPrompt) => void
20
21function getImageSrc(image: { url?: string; b64Json?: string }): string {
22 if (image.url) return image.url
23 if (image.b64Json) return `data:image/png;base64,${image.b64Json}`
24 return ''
25}
26
27const falModels = IMAGE_MODELS.filter((m) => m.provider === 'fal')
28const geminiModels = IMAGE_MODELS.filter((m) => m.provider === 'gemini')
29const xaiModels = IMAGE_MODELS.filter((m) => m.provider === 'xai')
30const byteplusModels = IMAGE_MODELS.filter((m) => m.provider === 'byteplus')
31
32export default function ImageGenerator({
33 onImageGenerated,
34}: ImageGeneratorProps) {
35 const [prompt, setPrompt] = useState('')
36 const [selectedModel, setSelectedModel] = useState<string>('all')
37 const [images, setImages] = useState<Array<AttachedMedia>>([])
38 /** Whether anything has been generated for the current model selection. */
39 const [submitted, setSubmitted] = useState(false)
40 const [running, setRunning] = useState<Record<string, boolean>>({})
41 const fileInputRef = useRef<HTMLInputElement>(null)
42 // Generation is started from the click, not from an effect on the cards:
43 // a hook only exists inside a mounted component, so the cards mount with
44 // the picker and hand the parent a way to run them.
45 const runnersRef = useRef(new Map<string, ImageRunner>())
46
47 const currentModel = IMAGE_MODELS.find((m) => m.id === selectedModel)
48 const activeModels =
49 selectedModel === 'all'
50 ? IMAGE_MODELS
51 : IMAGE_MODELS.filter((model) => model.id === selectedModel)
52 // Each card owns its own generation, so the form's busy state is the union
53 // of what the cards report.
54 const isLoading = Object.values(running).some(Boolean)
55
56 // When images are attached, send an ordered parts array (text first, then one
57 // image part per attachment). Otherwise send the plain string. Only image-capable
58 // models accept image inputs — unsupported models surface a server error.
59 const buildPrompt = (): MediaPrompt => {
60 if (images.length === 0) return prompt
61 return [
62 { type: 'text', content: prompt },
63 ...images.map((image) => toImagePart(image, { role: 'reference' })),
64 ]
65 }
66
67 const handleImageSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
68 const files = Array.from(e.target.files ?? [])
69 if (fileInputRef.current) fileInputRef.current.value = ''
70 if (files.length === 0) return
71 const attached = await Promise.all(files.map((file) => readMediaFile(file)))
72 setImages((prev) => [...prev, ...attached])
73 }
74
75 const removeImage = (id: string) => {
76 setImages((prev) => prev.filter((image) => image.id !== id))
77 }
78
79 const handleRunningChange = useCallback((modelId: string, value: boolean) => {
80 setRunning((prev) =>
81 prev[modelId] === value ? prev : { ...prev, [modelId]: value },
82 )
83 }, [])
84
85 const registerRunner = useCallback(
86 (modelId: string, run: ImageRunner | null) => {
87 if (run) runnersRef.current.set(modelId, run)
88 else runnersRef.current.delete(modelId)
89 },
90 [],
91 )
92
93 const handleGenerate = () => {
94 if (!prompt.trim()) return
95 const built = buildPrompt()
96 setSubmitted(true)
97 for (const model of activeModels) {
98 runnersRef.current.get(model.id)?.(built)
99 }
100 }
101
102 return (
103 <div className="space-y-6">
104 <div className="space-y-4">
105 <div>
106 <label className="block text-sm font-medium text-gray-300 mb-2">
107 Model
108 </label>
109 <select
110 value={selectedModel}
111 onChange={(e) => {
112 setSelectedModel(e.target.value)
113 // The results below belong to the models that produced them.
114 setSubmitted(false)
115 setRunning({})
116 }}
117 disabled={isLoading}
118 className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent disabled:opacity-50"
119 >
120 <option value="all">All Models</option>
121 <optgroup label="fal.ai">
122 {falModels.map((model) => (
123 <option key={model.id} value={model.id}>
124 {model.name}
125 </option>
126 ))}
127 </optgroup>
128 <optgroup label="Gemini">
129 {geminiModels.map((model) => (
130 <option key={model.id} value={model.id}>
131 {model.name}
132 </option>
133 ))}
134 </optgroup>
135 <optgroup label="xAI (direct)">
136 {xaiModels.map((model) => (
137 <option key={model.id} value={model.id}>
138 {model.name}
139 </option>
140 ))}
141 </optgroup>
142 <optgroup label="BytePlus (direct)">
143 {byteplusModels.map((model) => (
144 <option key={model.id} value={model.id}>
145 {model.name}
146 </option>
147 ))}
148 </optgroup>
149 </select>
150 {currentModel && selectedModel !== 'all' && (
151 <p className="mt-1 text-xs text-gray-500">
152 {currentModel.description}
153 </p>
154 )}
155 </div>
156
157 <div>
158 <div className="flex items-center justify-between mb-2">
159 <label className="text-sm font-medium text-gray-300">Prompt</label>
160 <button
161 onClick={() => setPrompt(getRandomImagePrompt())}
162 disabled={isLoading}
163 className="flex items-center gap-1.5 px-3 py-1 text-xs font-medium text-purple-400 hover:text-purple-300 bg-purple-500/10 hover:bg-purple-500/20 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
164 >
165 <Shuffle className="w-3.5 h-3.5" />
166 Shuffle
167 </button>
168 </div>
169 <textarea
170 value={prompt}
171 onChange={(e) => setPrompt(e.target.value)}
172 placeholder="Describe the image you want to generate..."
173 className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent resize-none"
174 rows={3}
175 disabled={isLoading}
176 />
177 </div>
178
179 <div>
180 <div className="flex items-center justify-between mb-2">
181 <label className="text-sm font-medium text-gray-300">
182 Reference Images
183 </label>
184 <span className="text-xs text-gray-500">
185 Sent as image prompt parts with role "reference" —
186 accepted by the Gemini multimodal models (uploaded once via the
187 Gemini Files API), xAI Imagine and Seedream
188 </span>
189 </div>
190 <div className="flex flex-wrap gap-2">
191 {images.map((image) => (
192 <div
193 key={image.id}
194 className="relative w-20 h-20 rounded-lg overflow-hidden border border-gray-700"
195 >
196 <img
197 src={image.dataUrl}
198 alt={image.name}
199 className="w-full h-full object-cover"
200 />
201 <button
202 onClick={() => removeImage(image.id)}
203 disabled={isLoading}
204 className="absolute top-1 right-1 p-0.5 bg-gray-900/80 hover:bg-gray-800 rounded-full text-white disabled:opacity-50"
205 aria-label={`Remove ${image.name}`}
206 >
207 <X className="w-3.5 h-3.5" />
208 </button>
209 </div>
210 ))}
211 <button
212 onClick={() => fileInputRef.current?.click()}
213 disabled={isLoading}
214 className="w-20 h-20 flex flex-col items-center justify-center gap-1 border-2 border-dashed border-gray-600 hover:border-gray-500 rounded-lg text-gray-400 hover:text-gray-300 transition-colors disabled:opacity-50"
215 >
216 <Plus className="w-5 h-5" />
217 <span className="text-xs">Add</span>
218 </button>
219 </div>
220 <input
221 ref={fileInputRef}
222 type="file"
223 accept="image/*"
224 multiple
225 onChange={handleImageSelect}
226 className="hidden"
227 />
228 </div>
229
230 <button
231 onClick={handleGenerate}
232 disabled={isLoading || !prompt.trim()}
233 className="w-full px-6 py-3 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-700 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
234 >
235 {isLoading ? (
236 <>
237 <Loader2 className="w-5 h-5 animate-spin" />
238 Generating...
239 </>
240 ) : (
241 <>
242 <ImageIcon className="w-5 h-5" />
243 Generate Image
244 </>
245 )}
246 </button>
247 </div>
248
249 <div className="space-y-6">
250 {submitted && (
251 <h3 className="text-lg font-medium text-white">
252 {activeModels.length > 1 ? 'Generated Images' : 'Generated Image'}
253 </h3>
254 )}
255 {activeModels.map((model) => (
256 <ImageModelCard
257 key={model.id}
258 model={model}
259 visible={submitted}
260 showTitle={activeModels.length > 1}
261 onRegister={registerRunner}
262 onRunningChange={handleRunningChange}
263 onImageGenerated={onImageGenerated}
264 />
265 ))}
266 </div>
267 </div>
268 )
269}
270
271/**
272 * One model's generation. `useGenerateImage` owns the request lifecycle, so
273 * the card only decides what to render for each of its states — there is no
274 * per-model status bookkeeping left in the parent.
275 */
276function ImageModelCard({
277 model,
278 visible,
279 showTitle,
280 onRegister,
281 onRunningChange,
282 onImageGenerated,
283}: {
284 model: ImageModel
285 visible: boolean
286 showTitle: boolean
287 onRegister: (modelId: string, run: ImageRunner | null) => void
288 onRunningChange: (modelId: string, running: boolean) => void
289 onImageGenerated?: (imageUrl: string) => void
290}) {
291 const { generate, result, isLoading, error } = useGenerateImage({
292 threadId: `image:${model.id}`,
293 // The model is fixed for this card, so the server function's per-model
294 // switch is picked here rather than being sent as a request field.
295 // `options.signal` is the hook's abort signal — forwarding it lets an
296 // unmount or a `stop()` cancel the request rather than orphan it.
297 byok,
298 byokProvider: () => toByokProvider(model.provider),
299 fetcher: (input, options) =>
300 callWithByok(
301 generateImageFn({
302 data: { prompt: input.prompt, model: model.id },
303 signal: options?.signal,
304 headers: options?.headers,
305 }),
306 ),
307 onResult: (generated) => {
308 const image = generated.images[0]
309 if (image) onImageGenerated?.(getImageSrc(image))
310 },
311 })
312
313 const run = useCallback(
314 (prompt: MediaPrompt) => {
315 // Deliberately not `reset()` first: reset stops the client, which clears
316 // the `isLoading` that makes a second `generate()` a no-op — that guard
317 // is what swallows a double-click. The stale result a failed re-run
318 // leaves behind is handled by the render gate below instead.
319 void generate({ prompt })
320 },
321 [generate],
322 )
323
324 useEffect(() => {
325 onRegister(model.id, run)
326 return () => onRegister(model.id, null)
327 }, [model.id, run, onRegister])
328
329 useEffect(() => {
330 onRunningChange(model.id, isLoading)
331 }, [model.id, isLoading, onRunningChange])
332
333 if (!visible) return null
334
335 const image = result?.images[0]
336
337 return (
338 <div className="space-y-2">
339 {showTitle && (
340 <h4 className="text-sm font-medium text-gray-300">{model.name}</h4>
341 )}
342 {isLoading && (
343 <div className="flex items-center gap-2 p-4 bg-gray-800 rounded-lg border border-gray-700">
344 <Loader2 className="w-5 h-5 animate-spin text-purple-400" />
345 <span className="text-gray-400">Generating...</span>
346 </div>
347 )}
348 {error && !isLoading && (
349 <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400">
350 {error.message}
351 </div>
352 )}
353 {/* `!error`: a failed re-run keeps the previous result on the hook, and
354 it must not render underneath the new error. */}
355 {image && !isLoading && !error && (
356 <>
357 <div className="rounded-lg overflow-hidden border border-gray-700">
358 <img
359 src={getImageSrc(image)}
360 alt={`Generated by ${model.name}`}
361 className="w-full h-auto"
362 />
363 </div>
364 {result?.usage?.billed && (
365 <p className="text-xs text-gray-500">
366 Billed {result.usage.billed.quantity}{' '}
367 {result.usage.billed.unit === 'units'
368 ? `fal unit${result.usage.billed.quantity === 1 ? '' : 's'}`
369 : result.usage.billed.unit}{' '}
370 — multiply by the endpoint unit price for USD cost
371 </p>
372 )}
373 </>
374 )}
375 </div>
376 )
377}