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

VideoGenUI.tsx

164 lines4.9 KB

1import { useRef, useState } from 'react'
2import {
3 useGenerateVideo,
4 fetchServerSentEvents,
5 fetchHttpStream,
6} from '@tanstack/ai-react'
7import { generateVideoFn } from '@/lib/server-functions'
8import type { MediaPrompt } from '@tanstack/ai'
9import type { Feature, Mode, Provider } from '@/lib/types'
10import type { VideoGenerateResult } from '@tanstack/ai-client'
11​
12interface VideoGenUIProps {
13 provider: Provider
14 mode: Mode
15 testId?: string
16 aimockPort?: number
17 /** Show a file input and send the prompt as multimodal parts (image-to-video). */
18 withImageInput?: boolean
19 /** Video feature variant — selects the adapter server-side (e.g. 'interactions-video' → Gemini Omni Flash). */
20 feature?: Feature
22​
23function fileToBase64(file: File): Promise<string> {
24 return new Promise((resolve, reject) => {
25 const reader = new FileReader()
26 reader.onload = () => {
27 const result = reader.result
28 if (typeof result !== 'string') {
29 reject(new Error('Unexpected FileReader result'))
30 return
31 }
32 const base64 = result.split(',')[1]
33 if (!base64) {
34 reject(new Error(`Unexpected data URL format: ${result.slice(0, 32)}…`))
35 return
36 }
37 resolve(base64)
38 }
39 reader.onerror = () => reject(new Error('Failed to read file'))
40 reader.readAsDataURL(file)
41 })
43​
44export function VideoGenUI({
45 provider,
46 mode,
47 testId,
48 aimockPort,
49 withImageInput,
50 feature,
51}: VideoGenUIProps) {
52 const [prompt, setPrompt] = useState('')
53 const [imageFile, setImageFile] = useState<File | null>(null)
54​
55 const connectionOptions = () => {
56 const body = { provider, testId, aimockPort, feature }
57​
58 if (mode === 'sse') {
59 return { connection: fetchServerSentEvents('/api/video'), body }
60 }
61 if (mode === 'http-stream') {
62 return { connection: fetchHttpStream('/api/video/stream'), body }
63 }
64 return {
65 fetcher: async (input: { prompt: MediaPrompt }) => {
66 return generateVideoFn({
67 data: { prompt: input.prompt, provider, aimockPort, testId, feature },
68 }) as Promise<VideoGenerateResult>
69 },
70 }
71 }
72​
73 const { generate, result, videoStatus, isLoading, error, status, runId } =
74 useGenerateVideo(connectionOptions())
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 video..."
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 {videoStatus && (
144 <span data-testid="video-status" className="text-gray-400 text-sm">
145 {videoStatus.status}
146 {videoStatus.progress != null && ` (${videoStatus.progress}%)`}
147 </span>
148 )}
149 {error && (
150 <div data-testid="generation-error" className="text-red-400 text-sm">
151 {error.message}
152 </div>
153 )}
154 {result && result.url && (
155 <video
156 data-testid="generated-video"
157 src={result.url}
158 controls
159 className="rounded border border-gray-700 max-w-lg"
160 />
161 )}
162 </div>
163 )