A transcript-viewer component from ElevenLabs UI.
From ElevenLabs UIMITSource
1"use client"
2
3import {
4 createContext,
5 useContext,
6 useMemo,
7 type ComponentPropsWithoutRef,
8 type ComponentPropsWithRef,
9 type HTMLAttributes,
10 type ReactNode,
11} from "react"
12import type { CharacterAlignmentResponseModel } from "@elevenlabs/elevenlabs-js/api/types/CharacterAlignmentResponseModel"
13import { Pause, Play } from "lucide-react"
14
15import { cn } from "@/lib/utils"
16import {
17 useTranscriptViewer,
18 type SegmentComposer,
19 type TranscriptSegment,
20 type TranscriptWord as TranscriptWordType,
21 type UseTranscriptViewerResult,
22} from "@/registry/elevenlabs-ui/hooks/use-transcript-viewer"
23import { Button } from "@/components/ui/button"
24import {
25 ScrubBarContainer,
26 ScrubBarProgress,
27 ScrubBarThumb,
28 ScrubBarTimeLabel,
29 ScrubBarTrack,
30} from "@/components/ui/scrub-bar"
31
32type TranscriptGap = Extract<TranscriptSegment, { kind: "gap" }>
33
34type TranscriptViewerContextValue = UseTranscriptViewerResult & {
35 audioProps: Omit<ComponentPropsWithRef<"audio">, "children" | "src">
36}
37
38const TranscriptViewerContext =
39 createContext<TranscriptViewerContextValue | null>(null)
40
41function useTranscriptViewerContext() {
42 const context = useContext(TranscriptViewerContext)
43 if (!context) {
44 throw new Error(
45 "useTranscriptViewerContext must be used within a TranscriptViewer"
46 )
47 }
48 return context
49}
50
51type TranscriptViewerProviderProps = {
52 value: TranscriptViewerContextValue
53 children: ReactNode
54}
55
56function TranscriptViewerProvider({
57 value,
58 children,
59}: TranscriptViewerProviderProps) {
60 return (
61 <TranscriptViewerContext.Provider value={value}>
62 {children}
63 </TranscriptViewerContext.Provider>
64 )
65}
66
67type AudioType =
68 | "audio/mpeg"
69 | "audio/wav"
70 | "audio/ogg"
71 | "audio/mp3"
72 | "audio/m4a"
73 | "audio/aac"
74 | "audio/webm"
75
76type TranscriptViewerContainerProps = {
77 audioSrc: string
78 audioType: AudioType
79 alignment: CharacterAlignmentResponseModel
80 segmentComposer?: SegmentComposer
81 hideAudioTags?: boolean
82 children?: ReactNode
83} & Omit<ComponentPropsWithoutRef<"div">, "children"> &
84 Pick<
85 Parameters<typeof useTranscriptViewer>[0],
86 "onPlay" | "onPause" | "onTimeUpdate" | "onEnded" | "onDurationChange"
87 >
88
89function TranscriptViewerContainer({
90 audioSrc,
91 audioType = "audio/mpeg",
92 alignment,
93 segmentComposer,
94 hideAudioTags = true,
95 children,
96 className,
97 onPlay,
98 onPause,
99 onTimeUpdate,
100 onEnded,
101 onDurationChange,
102 ...props
103}: TranscriptViewerContainerProps) {
104 const viewerState = useTranscriptViewer({
105 alignment,
106 hideAudioTags,
107 segmentComposer,
108 onPlay,
109 onPause,
110 onTimeUpdate,
111 onEnded,
112 onDurationChange,
113 })
114
115 const { audioRef } = viewerState
116
117 const audioProps = useMemo(
118 () => ({
119 ref: audioRef,
120 controls: false,
121 preload: "metadata" as const,
122 src: audioSrc,
123 children: <source src={audioSrc} type={audioType} />,
124 }),
125 [audioRef, audioSrc]
126 )
127
128 const contextValue = useMemo(
129 () => ({
130 ...viewerState,
131 audioProps,
132 }),
133 [viewerState, audioProps]
134 )
135
136 return (
137 <TranscriptViewerProvider value={contextValue}>
138 <div
139 data-slot="transcript-viewer-root"
140 className={cn("space-y-4 p-4", className)}
141 {...props}
142 >
143 {children}
144 </div>
145 </TranscriptViewerProvider>
146 )
147}
148
149type TranscriptViewerWordStatus = "spoken" | "unspoken" | "current"
150interface TranscriptViewerWordProps
151 extends Omit<HTMLAttributes<HTMLSpanElement>, "children"> {
152 word: TranscriptWordType
153 status: TranscriptViewerWordStatus
154 children?: ReactNode
155}
156
157function TranscriptViewerWord({
158 word,
159 status,
160 className,
161 children,
162 ...props
163}: TranscriptViewerWordProps) {
164 return (
165 <span
166 data-slot="transcript-word"
167 data-kind="word"
168 data-status={status}
169 className={cn(
170 "rounded-sm px-0.5 transition-colors",
171 status === "spoken" && "text-foreground",
172 status === "unspoken" && "text-muted-foreground",
173 status === "current" && "bg-primary text-primary-foreground",
174 className
175 )}
176 {...props}
177 >
178 {children ?? word.text}
179 </span>
180 )
181}
182
183interface TranscriptViewerWordsProps extends HTMLAttributes<HTMLDivElement> {
184 renderWord?: (props: {
185 word: TranscriptWordType
186 status: TranscriptViewerWordStatus
187 }) => ReactNode
188 renderGap?: (props: {
189 segment: TranscriptGap
190 status: TranscriptViewerWordStatus
191 }) => ReactNode
192 wordClassNames?: string
193 gapClassNames?: string
194}
195
196function TranscriptViewerWords({
197 className,
198 renderWord,
199 renderGap,
200 wordClassNames,
201 gapClassNames,
202 ...props
203}: TranscriptViewerWordsProps) {
204 const {
205 spokenSegments,
206 unspokenSegments,
207 currentWord,
208 segments,
209 duration,
210 currentTime,
211 } = useTranscriptViewerContext()
212
213 const nearEnd = useMemo(() => {
214 if (!duration) return false
215 return currentTime >= duration - 0.01
216 }, [currentTime, duration])
217
218 const segmentsWithStatus = useMemo(() => {
219 if (nearEnd) {
220 return segments.map((segment) => ({ segment, status: "spoken" as const }))
221 }
222
223 const entries: Array<{
224 segment: TranscriptSegment
225 status: TranscriptViewerWordStatus
226 }> = []
227
228 for (const segment of spokenSegments) {
229 entries.push({ segment, status: "spoken" })
230 }
231
232 if (currentWord) {
233 entries.push({ segment: currentWord, status: "current" })
234 }
235
236 for (const segment of unspokenSegments) {
237 entries.push({ segment, status: "unspoken" })
238 }
239
240 return entries
241 }, [spokenSegments, unspokenSegments, currentWord, nearEnd, segments])
242
243 return (
244 <div
245 data-slot="transcript-words"
246 className={cn("text-xl leading-relaxed", className)}
247 {...props}
248 >
249 {segmentsWithStatus.map(({ segment, status }) => {
250 if (segment.kind === "gap") {
251 const content = renderGap
252 ? renderGap({ segment, status })
253 : segment.text
254 return (
255 <span
256 key={`gap-${segment.segmentIndex}`}
257 data-kind="gap"
258 data-status={status}
259 className={cn(gapClassNames)}
260 >
261 {content}
262 </span>
263 )
264 }
265
266 if (renderWord) {
267 return (
268 <span
269 key={`word-${segment.segmentIndex}`}
270 data-kind="word"
271 data-status={status}
272 className={cn(wordClassNames)}
273 >
274 {renderWord({ word: segment, status })}
275 </span>
276 )
277 }
278
279 return (
280 <TranscriptViewerWord
281 key={`word-${segment.segmentIndex}`}
282 word={segment}
283 status={status}
284 className={wordClassNames}
285 />
286 )
287 })}
288 </div>
289 )
290}
291
292function TranscriptViewerAudio({
293 ...props
294}: ComponentPropsWithoutRef<"audio">) {
295 const { audioProps } = useTranscriptViewerContext()
296 return (
297 <audio
298 data-slot="transcript-audio"
299 {...audioProps}
300 {...props}
301 ref={audioProps.ref}
302 />
303 )
304}
305
306type RenderChildren = (state: { isPlaying: boolean }) => ReactNode
307
308type TranscriptViewerPlayPauseButtonProps = Omit<
309 ComponentPropsWithoutRef<typeof Button>,
310 "children"
311> & {
312 children?: ReactNode | RenderChildren
313}
314
315function TranscriptViewerPlayPauseButton({
316 className,
317 children,
318 onClick,
319 ...props
320}: TranscriptViewerPlayPauseButtonProps) {
321 const { isPlaying, play, pause } = useTranscriptViewerContext()
322 const Icon = isPlaying ? Pause : Play
323
324 const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
325 if (isPlaying) pause()
326 else play()
327 onClick?.(event)
328 }
329
330 const content =
331 typeof children === "function"
332 ? (children as RenderChildren)({ isPlaying })
333 : children
334
335 return (
336 <Button
337 data-slot="transcript-play-pause-button"
338 type="button"
339 variant="outline"
340 size="icon"
341 aria-label={isPlaying ? "Pause audio" : "Play audio"}
342 data-playing={isPlaying}
343 className={cn("cursor-pointer", className)}
344 onClick={handleClick}
345 {...props}
346 >
347 {content ?? <Icon className="size-5" />}
348 </Button>
349 )
350}
351
352type TranscriptViewerScrubBarProps = Omit<
353 ComponentPropsWithoutRef<typeof ScrubBarContainer>,
354 "duration" | "value" | "onScrub" | "onScrubStart" | "onScrubEnd"
355> & {
356 showTimeLabels?: boolean
357 labelsClassName?: string
358 trackClassName?: string
359 progressClassName?: string
360 thumbClassName?: string
361}
362
363/**
364 * A context-aware implementation of the scrub bar specific to the transcript viewer.
365 */
366function TranscriptViewerScrubBar({
367 className,
368 showTimeLabels = true,
369 labelsClassName,
370 trackClassName,
371 progressClassName,
372 thumbClassName,
373 ...props
374}: TranscriptViewerScrubBarProps) {
375 const { duration, currentTime, seekToTime, startScrubbing, endScrubbing } =
376 useTranscriptViewerContext()
377 return (
378 <ScrubBarContainer
379 data-slot="transcript-scrub-bar"
380 duration={duration}
381 value={currentTime}
382 onScrubStart={startScrubbing}
383 onScrubEnd={endScrubbing}
384 onScrub={seekToTime}
385 className={className}
386 {...props}
387 >
388 <div className="flex flex-1 flex-col gap-1">
389 <ScrubBarTrack className={trackClassName}>
390 <ScrubBarProgress className={progressClassName} />
391 <ScrubBarThumb className={thumbClassName} />
392 </ScrubBarTrack>
393 {showTimeLabels && (
394 <div
395 className={cn(
396 "text-muted-foreground flex items-center justify-between text-xs",
397 labelsClassName
398 )}
399 >
400 <ScrubBarTimeLabel time={currentTime} />
401 <ScrubBarTimeLabel time={duration - currentTime} />
402 </div>
403 )}
404 </div>
405 </ScrubBarContainer>
406 )
407}
408
409export {
410 TranscriptViewerContainer,
411 TranscriptViewerWords,
412 TranscriptViewerWord,
413 TranscriptViewerAudio,
414 TranscriptViewerPlayPauseButton,
415 TranscriptViewerScrubBar,
416 TranscriptViewerProvider,
417 useTranscriptViewerContext,
418}
419export type { CharacterAlignmentResponseModel }
420