A conversation-bar component from ElevenLabs UI.
From ElevenLabs UIMITSource
1"use client"
2
3import * as React from "react"
4import { useConversation } from "@elevenlabs/react"
5import {
6 ArrowUpIcon,
7 ChevronDown,
8 Keyboard,
9 Mic,
10 MicOff,
11 PhoneIcon,
12 XIcon,
13} from "lucide-react"
14
15import { cn } from "@/lib/utils"
16import { Button } from "@/components/ui/button"
17import { Card } from "@/components/ui/card"
18import { LiveWaveform } from "@/components/ui/live-waveform"
19import { Separator } from "@/components/ui/separator"
20import { Textarea } from "@/components/ui/textarea"
21
22export interface ConversationBarProps {
23 /**
24 * ElevenLabs Agent ID to connect to
25 */
26 agentId: string
27
28 /**
29 * Custom className for the container
30 */
31 className?: string
32
33 /**
34 * Custom className for the waveform
35 */
36 waveformClassName?: string
37
38 /**
39 * Callback when conversation connects
40 */
41 onConnect?: () => void
42
43 /**
44 * Callback when conversation disconnects
45 */
46 onDisconnect?: () => void
47
48 /**
49 * Callback when an error occurs
50 */
51 onError?: (error: Error) => void
52
53 /**
54 * Callback when a message is received
55 */
56 onMessage?: (message: { source: "user" | "ai"; message: string }) => void
57
58 /**
59 * Callback when user sends a message
60 */
61 onSendMessage?: (message: string) => void
62}
63
64export const ConversationBar = React.forwardRef<
65 HTMLDivElement,
66 ConversationBarProps
67>(
68 (
69 {
70 agentId,
71 className,
72 waveformClassName,
73 onConnect,
74 onDisconnect,
75 onError,
76 onMessage,
77 onSendMessage,
78 },
79 ref
80 ) => {
81 const [isMuted, setIsMuted] = React.useState(false)
82 const [agentState, setAgentState] = React.useState<
83 "disconnected" | "connecting" | "connected" | "disconnecting" | null
84 >("disconnected")
85 const [keyboardOpen, setKeyboardOpen] = React.useState(false)
86 const [textInput, setTextInput] = React.useState("")
87 const mediaStreamRef = React.useRef<MediaStream | null>(null)
88
89 const conversation = useConversation({
90 onConnect: () => {
91 onConnect?.()
92 },
93 onDisconnect: () => {
94 setAgentState("disconnected")
95 onDisconnect?.()
96 setKeyboardOpen(false)
97 },
98 onMessage: (message) => {
99 onMessage?.(message)
100 },
101 micMuted: isMuted,
102 onError: (error: unknown) => {
103 console.error("Error:", error)
104 setAgentState("disconnected")
105 const errorObj =
106 error instanceof Error
107 ? error
108 : new Error(
109 typeof error === "string" ? error : JSON.stringify(error)
110 )
111 onError?.(errorObj)
112 },
113 })
114
115 const getMicStream = React.useCallback(async () => {
116 if (mediaStreamRef.current) return mediaStreamRef.current
117
118 const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
119 mediaStreamRef.current = stream
120
121 return stream
122 }, [])
123
124 const startConversation = React.useCallback(async () => {
125 try {
126 setAgentState("connecting")
127
128 await getMicStream()
129
130 await conversation.startSession({
131 agentId,
132 connectionType: "webrtc",
133 onStatusChange: (status) => setAgentState(status.status),
134 })
135 } catch (error) {
136 console.error("Error starting conversation:", error)
137 setAgentState("disconnected")
138 onError?.(error as Error)
139 }
140 }, [conversation, getMicStream, agentId, onError])
141
142 const handleEndSession = React.useCallback(() => {
143 conversation.endSession()
144 setAgentState("disconnected")
145
146 if (mediaStreamRef.current) {
147 mediaStreamRef.current.getTracks().forEach((t) => t.stop())
148 mediaStreamRef.current = null
149 }
150 }, [conversation])
151
152 const toggleMute = React.useCallback(() => {
153 setIsMuted((prev) => !prev)
154 }, [])
155
156 const handleStartOrEnd = React.useCallback(() => {
157 if (agentState === "connected" || agentState === "connecting") {
158 handleEndSession()
159 } else if (agentState === "disconnected") {
160 startConversation()
161 }
162 }, [agentState, handleEndSession, startConversation])
163
164 const handleSendText = React.useCallback(() => {
165 if (!textInput.trim()) return
166
167 const messageToSend = textInput
168 conversation.sendUserMessage(messageToSend)
169 setTextInput("")
170 onSendMessage?.(messageToSend)
171 }, [conversation, textInput, onSendMessage])
172
173 const isConnected = agentState === "connected"
174
175 const handleTextChange = React.useCallback(
176 (e: React.ChangeEvent<HTMLTextAreaElement>) => {
177 const value = e.target.value
178 setTextInput(value)
179
180 if (value.trim() && isConnected) {
181 conversation.sendContextualUpdate(value)
182 }
183 },
184 [conversation, isConnected]
185 )
186
187 const handleKeyDown = React.useCallback(
188 (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
189 if (e.key === "Enter" && !e.shiftKey) {
190 e.preventDefault()
191 handleSendText()
192 }
193 },
194 [handleSendText]
195 )
196
197 React.useEffect(() => {
198 return () => {
199 if (mediaStreamRef.current) {
200 mediaStreamRef.current.getTracks().forEach((t) => t.stop())
201 }
202 }
203 }, [])
204
205 return (
206 <div
207 ref={ref}
208 className={cn("flex w-full items-end justify-center p-4", className)}
209 >
210 <Card className="m-0 w-full gap-0 border p-0 shadow-lg">
211 <div className="flex flex-col-reverse">
212 <div>
213 {keyboardOpen && <Separator />}
214 <div className="flex items-center justify-between gap-2 p-2">
215 <div className="h-8 w-[120px] md:h-10">
216 <div
217 className={cn(
218 "flex h-full items-center gap-2 rounded-md py-1",
219 "bg-foreground/5 text-foreground/70"
220 )}
221 >
222 <div className="h-full flex-1">
223 <div
224 className={cn(
225 "relative flex h-full w-full shrink-0 items-center justify-center overflow-hidden rounded-sm",
226 waveformClassName
227 )}
228 >
229 <LiveWaveform
230 key={
231 agentState === "disconnected" ? "idle" : "active"
232 }
233 active={isConnected && !isMuted}
234 processing={agentState === "connecting"}
235 barWidth={3}
236 barGap={1}
237 barRadius={4}
238 fadeEdges={true}
239 fadeWidth={24}
240 sensitivity={1.8}
241 smoothingTimeConstant={0.85}
242 height={20}
243 mode="static"
244 className={cn(
245 "h-full w-full transition-opacity duration-300",
246 agentState === "disconnected" && "opacity-0"
247 )}
248 />
249 {agentState === "disconnected" && (
250 <div className="absolute inset-0 flex items-center justify-center">
251 <span className="text-foreground/50 text-[10px] font-medium">
252 Customer Support
253 </span>
254 </div>
255 )}
256 </div>
257 </div>
258 </div>
259 </div>
260 <div className="flex items-center">
261 <Button
262 variant="ghost"
263 size="icon"
264 onClick={toggleMute}
265 aria-pressed={isMuted}
266 className={cn(isMuted ? "bg-foreground/5" : "")}
267 disabled={!isConnected}
268 >
269 {isMuted ? <MicOff /> : <Mic />}
270 </Button>
271 <Button
272 variant="ghost"
273 size="icon"
274 onClick={() => setKeyboardOpen((v) => !v)}
275 aria-pressed={keyboardOpen}
276 className="relative"
277 disabled={!isConnected}
278 >
279 <Keyboard
280 className={
281 "h-5 w-5 transform-gpu transition-all duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] " +
282 (keyboardOpen
283 ? "scale-75 opacity-0"
284 : "scale-100 opacity-100")
285 }
286 />
287 <ChevronDown
288 className={
289 "absolute inset-0 m-auto h-5 w-5 transform-gpu transition-all delay-50 duration-200 ease-[cubic-bezier(0.34,1.56,0.64,1)] " +
290 (keyboardOpen
291 ? "scale-100 opacity-100"
292 : "scale-75 opacity-0")
293 }
294 />
295 </Button>
296 <Separator orientation="vertical" className="mx-1 -my-2.5" />
297 <Button
298 variant="ghost"
299 size="icon"
300 onClick={handleStartOrEnd}
301 disabled={agentState === "disconnecting"}
302 >
303 {isConnected || agentState === "connecting" ? (
304 <XIcon className="h-5 w-5" />
305 ) : (
306 <PhoneIcon className="h-5 w-5" />
307 )}
308 </Button>
309 </div>
310 </div>
311 </div>
312
313 <div
314 className={cn(
315 "overflow-hidden transition-all duration-300 ease-out",
316 keyboardOpen ? "max-h-[120px]" : "max-h-0"
317 )}
318 >
319 <div className="relative px-2 pt-2 pb-2">
320 <Textarea
321 value={textInput}
322 onChange={handleTextChange}
323 onKeyDown={handleKeyDown}
324 placeholder="Enter your message..."
325 className="min-h-[100px] resize-none border-0 pr-12 shadow-none focus-visible:ring-0"
326 disabled={!isConnected}
327 />
328 <Button
329 size="icon"
330 variant="ghost"
331 onClick={handleSendText}
332 disabled={!textInput.trim() || !isConnected}
333 className="absolute right-3 bottom-3 h-8 w-8"
334 >
335 <ArrowUpIcon className="h-4 w-4" />
336 </Button>
337 </div>
338 </div>
339 </div>
340 </Card>
341 </div>
342 )
343 }
344)
345
346ConversationBar.displayName = "ConversationBar"
347