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

VideoGenUI.tsx

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