A speech-input component from ElevenLabs UI.
From ElevenLabs UIMITSource
1"use client"
2
3import {
4 Children,
5 createContext,
6 forwardRef,
7 isValidElement,
8 useCallback,
9 useContext,
10 useEffect,
11 useRef,
12 type ComponentPropsWithoutRef,
13 type ReactNode,
14} from "react"
15import { cva, VariantProps } from "class-variance-authority"
16import { motion } from "framer-motion"
17import { MicIcon, SquareIcon, XIcon } from "lucide-react"
18
19import { cn } from "@/lib/utils"
20import {
21 useScribe,
22 type AudioFormat,
23 type CommitStrategy,
24} from "@/registry/elevenlabs-ui/hooks/use-scribe"
25import { Button } from "@/components/ui/button"
26
27const buttonVariants = cva("!px-0", {
28 variants: {
29 size: {
30 default: "h-9 w-9",
31 sm: "h-8 w-8",
32 lg: "h-10 w-10",
33 },
34 },
35 defaultVariants: {
36 size: "default",
37 },
38})
39
40// Context for sharing state between compound components
41interface SpeechInputContextValue {
42 isConnected: boolean
43 isConnecting: boolean
44 transcript: string
45 partialTranscript: string
46 committedTranscripts: string[]
47 error: string | null
48 start: () => Promise<void>
49 stop: () => void
50 cancel: () => void
51 size: VariantProps<typeof buttonVariants>["size"]
52}
53
54const SpeechInputContext = createContext<SpeechInputContextValue | null>(null)
55
56function useSpeechInput() {
57 const context = useContext(SpeechInputContext)
58 if (!context) {
59 throw new Error(
60 "SpeechInput compound components must be used within a SpeechInput"
61 )
62 }
63 return context
64}
65
66// Root component
67interface SpeechInputEvent {
68 partialTranscript: string
69 committedTranscripts: string[]
70 transcript: string
71}
72
73interface SpeechInputProps {
74 children: ReactNode
75 getToken: () => Promise<string>
76 onChange?: (event: SpeechInputEvent) => void
77 onCancel?: (event: SpeechInputEvent) => void
78 onStart?: (event: SpeechInputEvent) => void
79 onStop?: (event: SpeechInputEvent) => void
80 className?: string
81 size?: VariantProps<typeof buttonVariants>["size"]
82
83 // Connection options
84 modelId?: string
85 baseUri?: string
86
87 // VAD options
88 commitStrategy?: CommitStrategy
89 vadSilenceThresholdSecs?: number
90 vadThreshold?: number
91 minSpeechDurationMs?: number
92 minSilenceDurationMs?: number
93 languageCode?: string
94
95 // Microphone options (for automatic microphone mode)
96 microphone?: {
97 deviceId?: string
98 echoCancellation?: boolean
99 noiseSuppression?: boolean
100 autoGainControl?: boolean
101 channelCount?: number
102 }
103
104 // Manual audio options
105 audioFormat?: AudioFormat
106 sampleRate?: number
107
108 // Error callbacks
109 onError?: (error: Error | Event) => void
110 onAuthError?: (data: { error: string }) => void
111 onQuotaExceededError?: (data: { error: string }) => void
112}
113
114const buildTranscript = ({
115 partialTranscript,
116 committedTranscripts,
117}: {
118 partialTranscript: string
119 committedTranscripts: string[]
120}): string => {
121 const committed = committedTranscripts.join(" ").trim()
122 const partial = partialTranscript.trim()
123
124 if (committed && partial) {
125 return `${committed} ${partial}`
126 }
127 return committed || partial
128}
129
130const buildEvent = ({
131 partialTranscript,
132 committedTranscripts,
133}: {
134 partialTranscript: string
135 committedTranscripts: string[]
136}): SpeechInputEvent => {
137 return {
138 partialTranscript,
139 committedTranscripts,
140 transcript: buildTranscript({ partialTranscript, committedTranscripts }),
141 }
142}
143
144const SpeechInput = forwardRef<HTMLDivElement, SpeechInputProps>(
145 function SpeechInput(
146 {
147 children,
148 getToken,
149 onChange,
150 onCancel,
151 onStart,
152 onStop,
153 className,
154 size = "default",
155 modelId = "scribe_v2_realtime",
156 baseUri,
157 commitStrategy,
158 vadSilenceThresholdSecs,
159 vadThreshold,
160 minSpeechDurationMs,
161 minSilenceDurationMs,
162 languageCode,
163 microphone = {
164 echoCancellation: true,
165 noiseSuppression: true,
166 },
167 audioFormat,
168 sampleRate,
169 onError,
170 onAuthError,
171 onQuotaExceededError,
172 },
173 ref
174 ) {
175 const transcriptsRef = useRef({
176 partialTranscript: "",
177 committedTranscripts: [] as string[],
178 })
179 const startRequestIdRef = useRef(0)
180
181 const scribe = useScribe({
182 modelId,
183 baseUri,
184 commitStrategy,
185 vadSilenceThresholdSecs,
186 vadThreshold,
187 minSpeechDurationMs,
188 minSilenceDurationMs,
189 languageCode,
190 audioFormat,
191 sampleRate,
192 microphone,
193 onPartialTranscript: (data) => {
194 transcriptsRef.current.partialTranscript = data.text
195 onChange?.(buildEvent(transcriptsRef.current))
196 },
197 onCommittedTranscript: (data) => {
198 transcriptsRef.current.committedTranscripts.push(data.text)
199 transcriptsRef.current.partialTranscript = ""
200 onChange?.(buildEvent(transcriptsRef.current))
201 },
202 onError,
203 onAuthError,
204 onQuotaExceededError,
205 })
206
207 const isConnecting = scribe.status === "connecting"
208
209 const start = useCallback(async () => {
210 const requestId = startRequestIdRef.current + 1
211 startRequestIdRef.current = requestId
212
213 transcriptsRef.current = {
214 partialTranscript: "",
215 committedTranscripts: [],
216 }
217 scribe.clearTranscripts()
218
219 try {
220 const token = await getToken()
221 if (startRequestIdRef.current !== requestId) {
222 return
223 }
224
225 await scribe.connect({
226 token,
227 })
228 if (startRequestIdRef.current !== requestId) {
229 scribe.disconnect()
230 return
231 }
232 onStart?.(buildEvent(transcriptsRef.current))
233 } catch {
234 // Error is handled by onError callback
235 }
236 // eslint-disable-next-line react-hooks/exhaustive-deps
237 }, [getToken, scribe, onStart, microphone])
238
239 const stop = () => {
240 startRequestIdRef.current += 1
241 scribe.disconnect()
242 onStop?.(buildEvent(transcriptsRef.current))
243 }
244
245 const cancel = () => {
246 startRequestIdRef.current += 1
247 const event = buildEvent(transcriptsRef.current)
248 scribe.disconnect()
249 scribe.clearTranscripts()
250 transcriptsRef.current = {
251 partialTranscript: "",
252 committedTranscripts: [],
253 }
254 onCancel?.(event)
255 }
256
257 const contextValue: SpeechInputContextValue = {
258 isConnected: scribe.isConnected,
259 isConnecting,
260 start,
261 stop,
262 cancel,
263 error: scribe.error,
264 size,
265 ...buildEvent({
266 partialTranscript: scribe.partialTranscript,
267 committedTranscripts: scribe.committedTranscripts.map((t) => t.text),
268 }),
269 }
270
271 useEffect(() => {
272 return () => {
273 startRequestIdRef.current += 1
274 scribe.disconnect()
275 }
276 }, [scribe.disconnect])
277
278 return (
279 <SpeechInputContext.Provider value={contextValue}>
280 <div
281 ref={ref}
282 className={cn(
283 "relative inline-flex items-center overflow-hidden rounded-lg border border-transparent transition-all duration-200",
284 scribe.isConnected
285 ? "bg-background dark:bg-muted border-input shadow-sm"
286 : "",
287 className
288 )}
289 >
290 {children}
291 </div>
292 </SpeechInputContext.Provider>
293 )
294 }
295)
296
297// Record button - toggles between mic icon and stop icon
298type SpeechInputRecordButtonProps = Omit<
299 ComponentPropsWithoutRef<typeof Button>,
300 "size"
301>
302
303const SpeechInputRecordButton = forwardRef<
304 HTMLButtonElement,
305 SpeechInputRecordButtonProps
306>(function SpeechInputRecordButton(
307 { className, onClick, variant = "ghost", disabled, ...props },
308 ref
309) {
310 const speechInput = useSpeechInput()
311
312 return (
313 <Button
314 ref={ref}
315 variant={variant}
316 onClick={(e) => {
317 if (speechInput.isConnected) {
318 speechInput.stop()
319 } else {
320 speechInput.start()
321 }
322 onClick?.(e)
323 }}
324 disabled={disabled ?? speechInput.isConnecting}
325 className={cn(
326 buttonVariants({ size: speechInput.size }),
327 "relative flex flex-shrink-0 items-center justify-center transition-all",
328 speechInput.isConnected && "scale-[80%]",
329 className
330 )}
331 aria-label={
332 speechInput.isConnected ? "Stop recording" : "Start recording"
333 }
334 {...props}
335 >
336 <div
337 className={cn(
338 "bg-primary absolute h-4 w-4 rounded-full transition-all duration-200",
339 speechInput.isConnecting
340 ? "scale-90 opacity-100"
341 : "scale-[60%] opacity-0"
342 )}
343 />
344 <SquareIcon
345 className={cn(
346 "text-destructive absolute h-4 w-4 fill-current transition-all duration-200",
347 !speechInput.isConnecting && speechInput.isConnected
348 ? "scale-100 opacity-100"
349 : "scale-[60%] opacity-0"
350 )}
351 />
352 <MicIcon
353 className={cn(
354 "absolute h-4 w-4 transition-all duration-200",
355 !speechInput.isConnecting && !speechInput.isConnected
356 ? "scale-100 opacity-100"
357 : "scale-[60%] opacity-0"
358 )}
359 />
360 </Button>
361 )
362})
363
364// Preview - shows the current transcript with partial
365type SpeechInputPreviewProps = ComponentPropsWithoutRef<"div"> & {
366 placeholder?: string
367}
368
369const SpeechInputPreview = forwardRef<HTMLDivElement, SpeechInputPreviewProps>(
370 function SpeechInputPreview(
371 { className, placeholder = "Listening...", ...props },
372 ref
373 ) {
374 const speechInput = useSpeechInput()
375
376 const displayText =
377 speechInput.transcript || speechInput.partialTranscript || placeholder
378 const showPlaceholder = !speechInput.transcript.trim()
379
380 return (
381 <div
382 ref={ref}
383 // @ts-expect-error inert is not yet in React types
384 inert={speechInput.isConnected ? undefined : ""}
385 className={cn(
386 "relative flex h-8 flex-shrink-0 items-center overflow-hidden text-sm transition-[opacity,transform,width] duration-200 ease-out",
387 showPlaceholder
388 ? "text-muted-foreground italic"
389 : "text-muted-foreground [mask-image:linear-gradient(to_right,transparent,black_16px,black_calc(100%-16px),transparent)]",
390 speechInput.isConnected ? "w-28 opacity-100" : "w-0 opacity-0",
391 className
392 )}
393 title={displayText}
394 aria-hidden={!speechInput.isConnected}
395 {...props}
396 >
397 <motion.p
398 key="text"
399 layout="position"
400 className={`absolute top-0 right-0 bottom-0 flex h-full min-w-full items-center px-0 whitespace-nowrap`}
401 >
402 {displayText}
403 </motion.p>
404 </div>
405 )
406 }
407)
408
409// Cancel button
410type SpeechInputCancelButtonProps = Omit<
411 ComponentPropsWithoutRef<typeof Button>,
412 "size"
413>
414
415const SpeechInputCancelButton = forwardRef<
416 HTMLButtonElement,
417 SpeechInputCancelButtonProps
418>(function SpeechInputCancelButton(
419 { className, onClick, variant = "ghost", ...props },
420 ref
421) {
422 const speechInput = useSpeechInput()
423
424 return (
425 <Button
426 ref={ref}
427 variant={variant}
428 // @ts-expect-error inert is not yet in React types
429 inert={speechInput.isConnected ? undefined : ""}
430 onClick={(e) => {
431 speechInput.cancel()
432 onClick?.(e)
433 }}
434 className={cn(
435 buttonVariants({ size: speechInput.size }),
436 "flex-shrink-0 transition-[opacity,transform,width] duration-200 ease-out",
437 speechInput.isConnected
438 ? "scale-[80%] opacity-100"
439 : "pointer-events-none w-0 scale-100 opacity-0",
440 className
441 )}
442 aria-label="Cancel recording"
443 {...props}
444 >
445 <XIcon className="h-3 w-3" />
446 </Button>
447 )
448})
449
450export {
451 SpeechInput,
452 SpeechInputRecordButton,
453 SpeechInputPreview,
454 SpeechInputCancelButton,
455 useSpeechInput,
456}
457