Open History to see the last commit
1import { useRef, useState } from 'react'
2import {
3 useGenerateImage,
4 fetchServerSentEvents,
5 fetchHttpStream,
6} from '@tanstack/ai-react'
7import { generateImageFn } from '@/lib/server-functions'
8import type { ImageGenerationResult, MediaPrompt } from '@tanstack/ai'
9import type { Mode, Provider } from '@/lib/types'
10
11interface ImageGenUIProps {
12 provider: Provider
13 mode: Mode
14 testId?: string
15 aimockPort?: number
16 /** Show a file input and send the prompt as multimodal parts (image-to-image). */
17 withImageInput?: boolean
18}
19
20function fileToBase64(file: File): Promise<string> {
21 return new Promise((resolve, reject) => {
22 const reader = new FileReader()
23 reader.onload = () => {
24 const result = reader.result
25 if (typeof result !== 'string') {
26 reject(new Error('Unexpected FileReader result'))
27 return
28 }
29 resolve(result.split(',')[1] ?? '')
30 }
31 reader.onerror = () => reject(new Error('Failed to read file'))
32 reader.readAsDataURL(file)
33 })
34}
35
36export function ImageGenUI({
37 provider,
38 mode,
39 testId,
40 aimockPort,
41 withImageInput,
42}: ImageGenUIProps) {
43 const [prompt, setPrompt] = useState('')
44 const [imageFile, setImageFile] = useState<File | null>(null)
45
46 const connectionOptions = () => {
47 const body = { provider, numberOfImages: 1, testId, aimockPort }
48
49 if (mode === 'sse') {
50 return { connection: fetchServerSentEvents('/api/image'), body }
51 }
52 if (mode === 'http-stream') {
53 return { connection: fetchHttpStream('/api/image/stream'), body }
54 }
55 return {
56 fetcher: async (input: { prompt: MediaPrompt }) => {
57 return generateImageFn({
58 data: {
59 prompt: input.prompt,
60 provider,
61 numberOfImages: 1,
62 aimockPort,
63 testId,
64 },
65 }) as Promise<ImageGenerationResult>
66 },
67 }
68 }
69
70 const { generate, result, isLoading, error, status, runId } =
71 useGenerateImage(connectionOptions())
72 const activeTuple = useRef({ runId: '', status: 'idle', isLoading: false })
73 if (runId && status === 'generating' && isLoading) {
74 activeTuple.current = { runId, status, isLoading }
75 }
76
77 const handleGenerate = async () => {
78 if (!imageFile) {
79 await generate({ prompt })
80 return
81 }
82 const base64 = await fileToBase64(imageFile)
83 await generate({
84 prompt: [
85 { type: 'text', content: prompt },
86 {
87 type: 'image',
88 source: { type: 'data', value: base64, mimeType: imageFile.type },
89 },
90 ],
91 })
92 }
93
94 return (
95 <div className="p-4 space-y-4">
96 <output data-testid="active-run-id">{activeTuple.current.runId}</output>
97 <output data-testid="active-status">{activeTuple.current.status}</output>
98 <output data-testid="active-loading">
99 {String(activeTuple.current.isLoading)}
100 </output>
101 <output data-testid="final-run-id">{runId ?? ''}</output>
102 <div className="flex gap-2">
103 <input
104 data-testid="prompt-input"
105 type="text"
106 value={prompt}
107 onChange={(e) => setPrompt(e.target.value)}
108 placeholder="Describe the image..."
109 className="flex-1 bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm"
110 />
111 <button
112 data-testid="generate-button"
113 onClick={handleGenerate}
114 disabled={!prompt.trim() || isLoading}
115 className="px-4 py-2 bg-orange-500 text-white rounded text-sm font-medium disabled:opacity-50"
116 >
117 Generate
118 </button>
119 </div>
120 {withImageInput && (
121 <input
122 data-testid="image-input"
123 type="file"
124 accept="image/*"
125 onChange={(e) => setImageFile(e.target.files?.[0] ?? null)}
126 className="text-sm text-gray-400"
127 />
128 )}
129 <div data-testid="generation-status">
130 {status === 'idle'
131 ? 'idle'
132 : isLoading
133 ? 'loading'
134 : error
135 ? 'error'
136 : result
137 ? 'complete'
138 : 'idle'}
139 </div>
140 {error && (
141 <div data-testid="generation-error" className="text-red-400 text-sm">
142 {error.message}
143 </div>
144 )}
145 {result && (
146 <div className="grid grid-cols-2 gap-4">
147 {result.images.map((img, i) => (
148 <img
149 key={i}
150 data-testid="generated-image"
151 src={img.url || `data:image/png;base64,${img.b64Json}`}
152 alt={`Generated ${i + 1}`}
153 className="rounded border border-gray-700"
154 />
155 ))}
156 </div>
157 )}
158 </div>
159 )
160}