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({
72 threadId: testId ?? 'image-gen',
73 ...connectionOptions(),
74 })
75 const activeTuple = useRef({ runId: '', status: 'idle', isLoading: false })
76 if (runId && status === 'generating' && isLoading) {
77 activeTuple.current = { runId, status, isLoading }
78 }
79
80 const handleGenerate = async () => {
81 if (!imageFile) {
82 await generate({ prompt })
83 return
84 }
85 const base64 = await fileToBase64(imageFile)
86 await generate({
87 prompt: [
88 { type: 'text', content: prompt },
89 {
90 type: 'image',
91 source: { type: 'data', value: base64, mimeType: imageFile.type },
92 },
93 ],
94 })
95 }
96
97 return (
98 <div className="p-4 space-y-4">
99 <output data-testid="active-run-id">{activeTuple.current.runId}</output>
100 <output data-testid="active-status">{activeTuple.current.status}</output>
101 <output data-testid="active-loading">
102 {String(activeTuple.current.isLoading)}
103 </output>
104 <output data-testid="final-run-id">{runId ?? ''}</output>
105 <div className="flex gap-2">
106 <input
107 data-testid="prompt-input"
108 type="text"
109 value={prompt}
110 onChange={(e) => setPrompt(e.target.value)}
111 placeholder="Describe the image..."
112 className="flex-1 bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm"
113 />
114 <button
115 data-testid="generate-button"
116 onClick={handleGenerate}
117 disabled={!prompt.trim() || isLoading}
118 className="px-4 py-2 bg-orange-500 text-white rounded text-sm font-medium disabled:opacity-50"
119 >
120 Generate
121 </button>
122 </div>
123 {withImageInput && (
124 <input
125 data-testid="image-input"
126 type="file"
127 accept="image/*"
128 onChange={(e) => setImageFile(e.target.files?.[0] ?? null)}
129 className="text-sm text-gray-400"
130 />
131 )}
132 <div data-testid="generation-status">
133 {status === 'idle'
134 ? 'idle'
135 : isLoading
136 ? 'loading'
137 : error
138 ? 'error'
139 : result
140 ? 'complete'
141 : 'idle'}
142 </div>
143 {error && (
144 <div data-testid="generation-error" className="text-red-400 text-sm">
145 {error.message}
146 </div>
147 )}
148 {result && (
149 <div className="grid grid-cols-2 gap-4">
150 {result.images.map((img, i) => (
151 <img
152 key={i}
153 data-testid="generated-image"
154 src={img.url || `data:image/png;base64,${img.b64Json}`}
155 alt={`Generated ${i + 1}`}
156 className="rounded border border-gray-700"
157 />
158 ))}
159 </div>
160 )}
161 </div>
162 )
163}