A waveform component from ElevenLabs UI.
From ElevenLabs UIMITSource
1"use client"
2
3import {
4 useCallback,
5 useEffect,
6 useMemo,
7 useRef,
8 useState,
9 type HTMLAttributes,
10} from "react"
11
12import { cn } from "@/lib/utils"
13
14export type WaveformProps = HTMLAttributes<HTMLDivElement> & {
15 data?: number[]
16 barWidth?: number
17 barHeight?: number
18 barGap?: number
19 barRadius?: number
20 barColor?: string
21 fadeEdges?: boolean
22 fadeWidth?: number
23 height?: string | number
24 active?: boolean
25 onBarClick?: (index: number, value: number) => void
26}
27
28export const Waveform = ({
29 data = [],
30 barWidth = 4,
31 barHeight: baseBarHeight = 4,
32 barGap = 2,
33 barRadius = 2,
34 barColor,
35 fadeEdges = true,
36 fadeWidth = 24,
37 height = 128,
38 onBarClick,
39 className,
40 ...props
41}: WaveformProps) => {
42 const canvasRef = useRef<HTMLCanvasElement>(null)
43 const containerRef = useRef<HTMLDivElement>(null)
44 const heightStyle = typeof height === "number" ? `${height}px` : height
45
46 useEffect(() => {
47 const canvas = canvasRef.current
48 const container = containerRef.current
49 if (!canvas || !container) return
50
51 const resizeObserver = new ResizeObserver(() => {
52 const rect = container.getBoundingClientRect()
53 const dpr = window.devicePixelRatio || 1
54
55 canvas.width = rect.width * dpr
56 canvas.height = rect.height * dpr
57 canvas.style.width = `${rect.width}px`
58 canvas.style.height = `${rect.height}px`
59
60 const ctx = canvas.getContext("2d")
61 if (ctx) {
62 ctx.scale(dpr, dpr)
63 renderWaveform()
64 }
65 })
66
67 const renderWaveform = () => {
68 const ctx = canvas.getContext("2d")
69 if (!ctx) return
70
71 const rect = canvas.getBoundingClientRect()
72 ctx.clearRect(0, 0, rect.width, rect.height)
73
74 const computedBarColor =
75 barColor ||
76 getComputedStyle(canvas).getPropertyValue("--foreground") ||
77 "#000"
78
79 const barCount = Math.floor(rect.width / (barWidth + barGap))
80 const centerY = rect.height / 2
81
82 for (let i = 0; i < barCount; i++) {
83 const dataIndex = Math.floor((i / barCount) * data.length)
84 const value = data[dataIndex] || 0
85 const barHeight = Math.max(baseBarHeight, value * rect.height * 0.8)
86 const x = i * (barWidth + barGap)
87 const y = centerY - barHeight / 2
88
89 ctx.fillStyle = computedBarColor
90 ctx.globalAlpha = 0.3 + value * 0.7
91
92 if (barRadius > 0) {
93 ctx.beginPath()
94 ctx.roundRect(x, y, barWidth, barHeight, barRadius)
95 ctx.fill()
96 } else {
97 ctx.fillRect(x, y, barWidth, barHeight)
98 }
99 }
100
101 if (fadeEdges && fadeWidth > 0 && rect.width > 0) {
102 const gradient = ctx.createLinearGradient(0, 0, rect.width, 0)
103 const fadePercent = Math.min(0.2, fadeWidth / rect.width)
104
105 gradient.addColorStop(0, "rgba(255,255,255,1)")
106 gradient.addColorStop(fadePercent, "rgba(255,255,255,0)")
107 gradient.addColorStop(1 - fadePercent, "rgba(255,255,255,0)")
108 gradient.addColorStop(1, "rgba(255,255,255,1)")
109
110 ctx.globalCompositeOperation = "destination-out"
111 ctx.fillStyle = gradient
112 ctx.fillRect(0, 0, rect.width, rect.height)
113 ctx.globalCompositeOperation = "source-over"
114 }
115
116 ctx.globalAlpha = 1
117 }
118
119 resizeObserver.observe(container)
120 renderWaveform()
121
122 return () => resizeObserver.disconnect()
123 }, [
124 data,
125 barWidth,
126 baseBarHeight,
127 barGap,
128 barRadius,
129 barColor,
130 fadeEdges,
131 fadeWidth,
132 ])
133
134 const handleClick = (e: React.MouseEvent<HTMLCanvasElement>) => {
135 if (!onBarClick) return
136
137 const rect = canvasRef.current?.getBoundingClientRect()
138 if (!rect) return
139
140 const x = e.clientX - rect.left
141 const barIndex = Math.floor(x / (barWidth + barGap))
142 const dataIndex = Math.floor(
143 (barIndex * data.length) / Math.floor(rect.width / (barWidth + barGap))
144 )
145
146 if (dataIndex >= 0 && dataIndex < data.length) {
147 onBarClick(dataIndex, data[dataIndex])
148 }
149 }
150
151 return (
152 <div
153 className={cn("relative", className)}
154 ref={containerRef}
155 style={{ height: heightStyle }}
156 {...props}
157 >
158 <canvas
159 className="block h-full w-full"
160 onClick={handleClick}
161 ref={canvasRef}
162 />
163 </div>
164 )
165}
166
167export type ScrollingWaveformProps = Omit<
168 WaveformProps,
169 "data" | "onBarClick"
170> & {
171 speed?: number
172 barCount?: number
173 data?: number[]
174}
175
176export const ScrollingWaveform = ({
177 speed = 50,
178 barCount = 60,
179 barWidth = 4,
180 barHeight: baseBarHeight = 4,
181 barGap = 2,
182 barRadius = 2,
183 barColor,
184 fadeEdges = true,
185 fadeWidth = 24,
186 height = 128,
187 data,
188 className,
189 ...props
190}: ScrollingWaveformProps) => {
191 const canvasRef = useRef<HTMLCanvasElement>(null)
192 const containerRef = useRef<HTMLDivElement>(null)
193 const barsRef = useRef<Array<{ x: number; height: number }>>([])
194 const animationRef = useRef<number>(0)
195 const lastTimeRef = useRef<number>(0)
196 const seedRef = useRef(Math.random())
197 const dataIndexRef = useRef(0)
198 const heightStyle = typeof height === "number" ? `${height}px` : height
199
200 useEffect(() => {
201 const canvas = canvasRef.current
202 const container = containerRef.current
203 if (!canvas || !container) return
204
205 const resizeObserver = new ResizeObserver(() => {
206 const rect = container.getBoundingClientRect()
207 const dpr = window.devicePixelRatio || 1
208
209 canvas.width = rect.width * dpr
210 canvas.height = rect.height * dpr
211 canvas.style.width = `${rect.width}px`
212 canvas.style.height = `${rect.height}px`
213
214 const ctx = canvas.getContext("2d")
215 if (ctx) {
216 ctx.scale(dpr, dpr)
217 }
218
219 if (barsRef.current.length === 0) {
220 const step = barWidth + barGap
221 let currentX = rect.width
222 let index = 0
223 const seededRandom = (i: number) => {
224 const x = Math.sin(seedRef.current * 10000 + i) * 10000
225 return x - Math.floor(x)
226 }
227 while (currentX > -step) {
228 barsRef.current.push({
229 x: currentX,
230 height: 0.2 + seededRandom(index++) * 0.6,
231 })
232 currentX -= step
233 }
234 }
235 })
236
237 resizeObserver.observe(container)
238 return () => resizeObserver.disconnect()
239 }, [barWidth, barGap])
240
241 useEffect(() => {
242 const canvas = canvasRef.current
243 if (!canvas) return
244
245 const ctx = canvas.getContext("2d")
246 if (!ctx) return
247
248 const animate = (currentTime: number) => {
249 const deltaTime = lastTimeRef.current
250 ? (currentTime - lastTimeRef.current) / 1000
251 : 0
252 lastTimeRef.current = currentTime
253
254 const rect = canvas.getBoundingClientRect()
255 ctx.clearRect(0, 0, rect.width, rect.height)
256
257 const computedBarColor =
258 barColor ||
259 getComputedStyle(canvas).getPropertyValue("--foreground") ||
260 "#000"
261
262 const step = barWidth + barGap
263 for (let i = 0; i < barsRef.current.length; i++) {
264 barsRef.current[i].x -= speed * deltaTime
265 }
266
267 barsRef.current = barsRef.current.filter(
268 (bar) => bar.x + barWidth > -step
269 )
270
271 while (
272 barsRef.current.length === 0 ||
273 barsRef.current[barsRef.current.length - 1].x < rect.width
274 ) {
275 const lastBar = barsRef.current[barsRef.current.length - 1]
276 const nextX = lastBar ? lastBar.x + step : rect.width
277
278 let newHeight: number
279 if (data && data.length > 0) {
280 newHeight = data[dataIndexRef.current % data.length] || 0.1
281 dataIndexRef.current = (dataIndexRef.current + 1) % data.length
282 } else {
283 const time = Date.now() / 1000
284 const uniqueIndex = barsRef.current.length + time * 0.01
285 const seededRandom = (index: number) => {
286 const x = Math.sin(seedRef.current * 10000 + index * 137.5) * 10000
287 return x - Math.floor(x)
288 }
289 const wave1 = Math.sin(uniqueIndex * 0.1) * 0.2
290 const wave2 = Math.cos(uniqueIndex * 0.05) * 0.15
291 const randomComponent = seededRandom(uniqueIndex) * 0.4
292 newHeight = Math.max(
293 0.1,
294 Math.min(0.9, 0.3 + wave1 + wave2 + randomComponent)
295 )
296 }
297
298 barsRef.current.push({
299 x: nextX,
300 height: newHeight,
301 })
302 if (barsRef.current.length > barCount * 2) break
303 }
304
305 const centerY = rect.height / 2
306 for (const bar of barsRef.current) {
307 if (bar.x < rect.width && bar.x + barWidth > 0) {
308 const barHeight = Math.max(
309 baseBarHeight,
310 bar.height * rect.height * 0.6
311 )
312 const y = centerY - barHeight / 2
313
314 ctx.fillStyle = computedBarColor
315 ctx.globalAlpha = 0.3 + bar.height * 0.7
316
317 if (barRadius > 0) {
318 ctx.beginPath()
319 ctx.roundRect(bar.x, y, barWidth, barHeight, barRadius)
320 ctx.fill()
321 } else {
322 ctx.fillRect(bar.x, y, barWidth, barHeight)
323 }
324 }
325 }
326
327 if (fadeEdges && fadeWidth > 0) {
328 const gradient = ctx.createLinearGradient(0, 0, rect.width, 0)
329 const fadePercent = Math.min(0.2, fadeWidth / rect.width)
330
331 gradient.addColorStop(0, "rgba(255,255,255,1)")
332 gradient.addColorStop(fadePercent, "rgba(255,255,255,0)")
333 gradient.addColorStop(1 - fadePercent, "rgba(255,255,255,0)")
334 gradient.addColorStop(1, "rgba(255,255,255,1)")
335
336 ctx.globalCompositeOperation = "destination-out"
337 ctx.fillStyle = gradient
338 ctx.fillRect(0, 0, rect.width, rect.height)
339 ctx.globalCompositeOperation = "source-over"
340 }
341
342 ctx.globalAlpha = 1
343
344 animationRef.current = requestAnimationFrame(animate)
345 }
346
347 animationRef.current = requestAnimationFrame(animate)
348
349 return () => {
350 if (animationRef.current) {
351 cancelAnimationFrame(animationRef.current)
352 }
353 }
354 }, [
355 speed,
356 barCount,
357 barWidth,
358 baseBarHeight,
359 barGap,
360 barRadius,
361 barColor,
362 fadeEdges,
363 fadeWidth,
364 data,
365 ])
366
367 return (
368 <div
369 className={cn("relative flex items-center", className)}
370 ref={containerRef}
371 style={{ height: heightStyle }}
372 {...props}
373 >
374 <canvas className="block h-full w-full" ref={canvasRef} />
375 </div>
376 )
377}
378
379export type AudioScrubberProps = WaveformProps & {
380 currentTime?: number
381 duration?: number
382 onSeek?: (time: number) => void
383 showHandle?: boolean
384}
385
386export const AudioScrubber = ({
387 data = [],
388 currentTime = 0,
389 duration = 100,
390 onSeek,
391 showHandle = true,
392 barWidth = 3,
393 barHeight,
394 barGap = 1,
395 barRadius = 1,
396 barColor,
397 height = 128,
398 className,
399 ...props
400}: AudioScrubberProps) => {
401 const [isDragging, setIsDragging] = useState(false)
402 const [localProgress, setLocalProgress] = useState(0)
403 const containerRef = useRef<HTMLDivElement>(null)
404
405 const waveformData =
406 data.length > 0
407 ? data
408 : Array.from({ length: 100 }, () => 0.2 + Math.random() * 0.6)
409
410 useEffect(() => {
411 if (!isDragging && duration > 0) {
412 setLocalProgress(currentTime / duration)
413 }
414 }, [currentTime, duration, isDragging])
415
416 const handleScrub = useCallback(
417 (clientX: number) => {
418 const container = containerRef.current
419 if (!container) return
420
421 const rect = container.getBoundingClientRect()
422 const x = Math.max(0, Math.min(clientX - rect.left, rect.width))
423 const progress = x / rect.width
424 const newTime = progress * duration
425
426 setLocalProgress(progress)
427 onSeek?.(newTime)
428 },
429 [duration, onSeek]
430 )
431
432 const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
433 e.preventDefault()
434 setIsDragging(true)
435 handleScrub(e.clientX)
436 }
437
438 useEffect(() => {
439 if (!isDragging) return
440
441 const handleMouseMove = (e: MouseEvent) => {
442 handleScrub(e.clientX)
443 }
444
445 const handleMouseUp = () => {
446 setIsDragging(false)
447 }
448
449 document.addEventListener("mousemove", handleMouseMove)
450 document.addEventListener("mouseup", handleMouseUp)
451
452 return () => {
453 document.removeEventListener("mousemove", handleMouseMove)
454 document.removeEventListener("mouseup", handleMouseUp)
455 }
456 }, [isDragging, duration, handleScrub])
457
458 const heightStyle = typeof height === "number" ? `${height}px` : height
459
460 return (
461 <div
462 aria-label="Audio waveform scrubber"
463 aria-valuemax={duration}
464 aria-valuemin={0}
465 aria-valuenow={currentTime}
466 className={cn("relative cursor-pointer select-none", className)}
467 onMouseDown={handleMouseDown}
468 ref={containerRef}
469 role="slider"
470 style={{ height: heightStyle }}
471 tabIndex={0}
472 {...props}
473 >
474 <Waveform
475 barColor={barColor}
476 barGap={barGap}
477 barRadius={barRadius}
478 barWidth={barWidth}
479 barHeight={barHeight}
480 data={waveformData}
481 fadeEdges={false}
482 />
483
484 <div
485 className="bg-primary/20 pointer-events-none absolute inset-y-0 left-0"
486 style={{ width: `${localProgress * 100}%` }}
487 />
488
489 <div
490 className="bg-primary pointer-events-none absolute top-0 bottom-0 w-0.5"
491 style={{ left: `${localProgress * 100}%` }}
492 />
493
494 {showHandle && (
495 <div
496 className="border-background bg-primary pointer-events-none absolute top-1/2 h-4 w-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 shadow-lg transition-transform hover:scale-110"
497 style={{ left: `${localProgress * 100}%` }}
498 />
499 )}
500 </div>
501 )
502}
503
504export type MicrophoneWaveformProps = WaveformProps & {
505 active?: boolean
506 processing?: boolean
507 fftSize?: number
508 smoothingTimeConstant?: number
509 sensitivity?: number
510 onError?: (error: Error) => void
511}
512
513export const MicrophoneWaveform = ({
514 active = false,
515 processing = false,
516 fftSize = 256,
517 smoothingTimeConstant = 0.8,
518 sensitivity = 1,
519 onError,
520 ...props
521}: MicrophoneWaveformProps) => {
522 const [data, setData] = useState<number[]>([])
523 const analyserRef = useRef<AnalyserNode | null>(null)
524 const audioContextRef = useRef<AudioContext | null>(null)
525 const streamRef = useRef<MediaStream | null>(null)
526 const animationIdRef = useRef<number | null>(null)
527 const processingAnimationRef = useRef<number | null>(null)
528 const lastActiveDataRef = useRef<number[]>([])
529 const transitionProgressRef = useRef(0)
530
531 useEffect(() => {
532 if (processing && !active) {
533 let time = 0
534 transitionProgressRef.current = 0
535
536 const animateProcessing = () => {
537 time += 0.03
538 transitionProgressRef.current = Math.min(
539 1,
540 transitionProgressRef.current + 0.02
541 )
542
543 const processingData = []
544 const barCount = 45
545
546 for (let i = 0; i < barCount; i++) {
547 const normalizedPosition = (i - barCount / 2) / (barCount / 2)
548 const centerWeight = 1 - Math.abs(normalizedPosition) * 0.4
549
550 const wave1 = Math.sin(time * 1.5 + i * 0.15) * 0.25
551 const wave2 = Math.sin(time * 0.8 - i * 0.1) * 0.2
552 const wave3 = Math.cos(time * 2 + i * 0.05) * 0.15
553 const combinedWave = wave1 + wave2 + wave3
554 const processingValue = (0.2 + combinedWave) * centerWeight
555
556 let finalValue = processingValue
557 if (
558 lastActiveDataRef.current.length > 0 &&
559 transitionProgressRef.current < 1
560 ) {
561 const lastDataIndex = Math.floor(
562 (i / barCount) * lastActiveDataRef.current.length
563 )
564 const lastValue = lastActiveDataRef.current[lastDataIndex] || 0
565 finalValue =
566 lastValue * (1 - transitionProgressRef.current) +
567 processingValue * transitionProgressRef.current
568 }
569
570 processingData.push(Math.max(0.05, Math.min(1, finalValue)))
571 }
572
573 setData(processingData)
574 processingAnimationRef.current =
575 requestAnimationFrame(animateProcessing)
576 }
577
578 animateProcessing()
579
580 return () => {
581 if (processingAnimationRef.current) {
582 cancelAnimationFrame(processingAnimationRef.current)
583 }
584 }
585 } else if (!active && !processing) {
586 if (data.length > 0) {
587 let fadeProgress = 0
588 const fadeToIdle = () => {
589 fadeProgress += 0.03
590 if (fadeProgress < 1) {
591 const fadedData = data.map((value) => value * (1 - fadeProgress))
592 setData(fadedData)
593 requestAnimationFrame(fadeToIdle)
594 } else {
595 setData([])
596 }
597 }
598 fadeToIdle()
599 }
600 return
601 }
602 }, [processing, active])
603
604 useEffect(() => {
605 if (!active) {
606 if (streamRef.current) {
607 streamRef.current.getTracks().forEach((track) => track.stop())
608 }
609 if (
610 audioContextRef.current &&
611 audioContextRef.current.state !== "closed"
612 ) {
613 audioContextRef.current.close()
614 }
615 if (animationIdRef.current) {
616 cancelAnimationFrame(animationIdRef.current)
617 }
618 return
619 }
620
621 const setupMicrophone = async () => {
622 try {
623 const stream = await navigator.mediaDevices.getUserMedia({
624 audio: true,
625 })
626 streamRef.current = stream
627
628 const audioContext = new (window.AudioContext ||
629 (window as unknown as { webkitAudioContext: typeof AudioContext })
630 .webkitAudioContext)()
631 const analyser = audioContext.createAnalyser()
632 analyser.fftSize = fftSize
633 analyser.smoothingTimeConstant = smoothingTimeConstant
634
635 const source = audioContext.createMediaStreamSource(stream)
636 source.connect(analyser)
637
638 audioContextRef.current = audioContext
639 analyserRef.current = analyser
640
641 const dataArray = new Uint8Array(analyser.frequencyBinCount)
642
643 const updateData = () => {
644 if (!analyserRef.current || !active) return
645
646 analyserRef.current.getByteFrequencyData(dataArray)
647
648 const startFreq = Math.floor(dataArray.length * 0.05)
649 const endFreq = Math.floor(dataArray.length * 0.4)
650 const relevantData = dataArray.slice(startFreq, endFreq)
651
652 const halfLength = Math.floor(relevantData.length / 2)
653 const normalizedData = []
654
655 for (let i = halfLength - 1; i >= 0; i--) {
656 const value = Math.min(1, (relevantData[i] / 255) * sensitivity)
657 normalizedData.push(value)
658 }
659
660 for (let i = 0; i < halfLength; i++) {
661 const value = Math.min(1, (relevantData[i] / 255) * sensitivity)
662 normalizedData.push(value)
663 }
664
665 setData(normalizedData)
666 lastActiveDataRef.current = normalizedData
667
668 animationIdRef.current = requestAnimationFrame(updateData)
669 }
670
671 updateData()
672 } catch (error) {
673 onError?.(error as Error)
674 }
675 }
676
677 setupMicrophone()
678
679 return () => {
680 if (streamRef.current) {
681 streamRef.current.getTracks().forEach((track) => track.stop())
682 }
683 if (
684 audioContextRef.current &&
685 audioContextRef.current.state !== "closed"
686 ) {
687 audioContextRef.current.close()
688 }
689 if (animationIdRef.current) {
690 cancelAnimationFrame(animationIdRef.current)
691 }
692 }
693 }, [active, fftSize, smoothingTimeConstant, sensitivity, onError])
694
695 return <Waveform data={data} {...props} />
696}
697
698export type StaticWaveformProps = WaveformProps & {
699 bars?: number
700 seed?: number
701}
702
703export const StaticWaveform = ({
704 bars = 40,
705 seed = 42,
706 ...props
707}: StaticWaveformProps) => {
708 const data = useMemo(() => {
709 const random = (seedValue: number) => {
710 const x = Math.sin(seedValue) * 10000
711 return x - Math.floor(x)
712 }
713
714 return Array.from({ length: bars }, (_, i) => 0.2 + random(seed + i) * 0.6)
715 }, [bars, seed])
716
717 return <Waveform data={data} {...props} />
718}
719
720export type LiveMicrophoneWaveformProps = Omit<
721 ScrollingWaveformProps,
722 "barCount"
723> & {
724 active?: boolean
725 fftSize?: number
726 smoothingTimeConstant?: number
727 sensitivity?: number
728 onError?: (error: Error) => void
729 historySize?: number
730 updateRate?: number
731 savedHistoryRef?: React.MutableRefObject<number[]>
732 dragOffset?: number
733 setDragOffset?: (offset: number) => void
734 enableAudioPlayback?: boolean
735 playbackRate?: number
736}
737
738export const LiveMicrophoneWaveform = ({
739 active = false,
740 fftSize = 256,
741 smoothingTimeConstant = 0.8,
742 sensitivity = 1,
743 onError,
744 historySize = 150,
745 updateRate = 50,
746 barWidth = 3,
747 barHeight: baseBarHeight = 4,
748 barGap = 1,
749 barRadius = 1,
750 barColor,
751 fadeEdges = true,
752 fadeWidth = 24,
753 height = 128,
754 className,
755 savedHistoryRef,
756 dragOffset: externalDragOffset,
757 setDragOffset: externalSetDragOffset,
758 enableAudioPlayback = true,
759 playbackRate = 1,
760 ...props
761}: LiveMicrophoneWaveformProps) => {
762 const canvasRef = useRef<HTMLCanvasElement>(null)
763 const containerRef = useRef<HTMLDivElement>(null)
764 const internalHistoryRef = useRef<number[]>([])
765 const historyRef = savedHistoryRef || internalHistoryRef
766 const analyserRef = useRef<AnalyserNode | null>(null)
767 const audioContextRef = useRef<AudioContext | null>(null)
768 const streamRef = useRef<MediaStream | null>(null)
769 const animationRef = useRef<number>(0)
770 const lastUpdateRef = useRef<number>(0)
771 const [internalDragOffset, setInternalDragOffset] = useState(0)
772 const [isDragging, setIsDragging] = useState(false)
773 const [playbackPosition, setPlaybackPosition] = useState<number | null>(null)
774 const dragStartXRef = useRef<number>(0)
775 const dragStartOffsetRef = useRef<number>(0)
776 const playbackStartTimeRef = useRef<number>(0)
777
778 // Audio recording and playback refs
779 const mediaRecorderRef = useRef<MediaRecorder | null>(null)
780 const audioChunksRef = useRef<Blob[]>([])
781 const audioBufferRef = useRef<AudioBuffer | null>(null)
782 const sourceNodeRef = useRef<AudioBufferSourceNode | null>(null)
783 const scrubSourceRef = useRef<AudioBufferSourceNode | null>(null)
784
785 // Use external drag state if provided, otherwise use internal
786 const dragOffset = externalDragOffset ?? internalDragOffset
787 const setDragOffset = externalSetDragOffset ?? setInternalDragOffset
788
789 const heightStyle = typeof height === "number" ? `${height}px` : height
790
791 useEffect(() => {
792 const canvas = canvasRef.current
793 const container = containerRef.current
794 if (!canvas || !container) return
795
796 const resizeObserver = new ResizeObserver(() => {
797 const rect = container.getBoundingClientRect()
798 const dpr = window.devicePixelRatio || 1
799
800 canvas.width = rect.width * dpr
801 canvas.height = rect.height * dpr
802 canvas.style.width = `${rect.width}px`
803 canvas.style.height = `${rect.height}px`
804
805 const ctx = canvas.getContext("2d")
806 if (ctx) {
807 ctx.scale(dpr, dpr)
808 }
809 })
810
811 resizeObserver.observe(container)
812 return () => resizeObserver.disconnect()
813 }, [])
814
815 useEffect(() => {
816 if (!active) {
817 if (
818 mediaRecorderRef.current &&
819 mediaRecorderRef.current.state !== "inactive"
820 ) {
821 mediaRecorderRef.current.stop()
822 }
823 if (streamRef.current) {
824 streamRef.current.getTracks().forEach((track) => track.stop())
825 }
826 // Process recorded audio when stopping
827 if (enableAudioPlayback && audioChunksRef.current.length > 0) {
828 const audioBlob = new Blob(audioChunksRef.current, {
829 type: "audio/webm",
830 })
831 processAudioBlob(audioBlob)
832 }
833 return
834 }
835
836 setDragOffset?.(0)
837 historyRef.current = []
838 audioChunksRef.current = []
839 audioBufferRef.current = null
840 setPlaybackPosition(null)
841
842 const setupMicrophone = async () => {
843 try {
844 const stream = await navigator.mediaDevices.getUserMedia({
845 audio: true,
846 })
847 streamRef.current = stream
848
849 const audioContext = new (window.AudioContext ||
850 (window as unknown as { webkitAudioContext: typeof AudioContext })
851 .webkitAudioContext)()
852 const analyser = audioContext.createAnalyser()
853 analyser.fftSize = fftSize
854 analyser.smoothingTimeConstant = smoothingTimeConstant
855
856 const source = audioContext.createMediaStreamSource(stream)
857 source.connect(analyser)
858
859 audioContextRef.current = audioContext
860 analyserRef.current = analyser
861
862 if (enableAudioPlayback) {
863 const mediaRecorder = new MediaRecorder(stream)
864 mediaRecorderRef.current = mediaRecorder
865
866 mediaRecorder.ondataavailable = (event) => {
867 if (event.data.size > 0) {
868 audioChunksRef.current.push(event.data)
869 }
870 }
871
872 mediaRecorder.start(100)
873 }
874 } catch (error) {
875 onError?.(error as Error)
876 }
877 }
878
879 setupMicrophone()
880
881 return () => {
882 if (
883 mediaRecorderRef.current &&
884 mediaRecorderRef.current.state !== "inactive"
885 ) {
886 mediaRecorderRef.current.stop()
887 }
888 if (streamRef.current) {
889 streamRef.current.getTracks().forEach((track) => track.stop())
890 }
891 if (sourceNodeRef.current) {
892 sourceNodeRef.current.stop()
893 }
894 if (scrubSourceRef.current) {
895 scrubSourceRef.current.stop()
896 }
897 }
898 }, [
899 active,
900 fftSize,
901 smoothingTimeConstant,
902 onError,
903 setDragOffset,
904 enableAudioPlayback,
905 historyRef,
906 ])
907
908 const processAudioBlob = async (blob: Blob) => {
909 try {
910 const arrayBuffer = await blob.arrayBuffer()
911 if (audioContextRef.current) {
912 const audioBuffer =
913 await audioContextRef.current.decodeAudioData(arrayBuffer)
914 audioBufferRef.current = audioBuffer
915 }
916 } catch (error) {
917 console.error("Error processing audio:", error)
918 }
919 }
920
921 const playScrubSound = useCallback(
922 (position: number, direction: number) => {
923 if (
924 !enableAudioPlayback ||
925 !audioBufferRef.current ||
926 !audioContextRef.current
927 )
928 return
929
930 if (scrubSourceRef.current) {
931 try {
932 scrubSourceRef.current.stop()
933 } catch {}
934 }
935
936 const source = audioContextRef.current.createBufferSource()
937 source.buffer = audioBufferRef.current
938
939 const speed = Math.abs(direction)
940 const playbackRate =
941 direction > 0
942 ? Math.min(3, 1 + speed * 0.1)
943 : Math.max(-3, -1 - speed * 0.1)
944
945 source.playbackRate.value = playbackRate
946
947 const filter = audioContextRef.current.createBiquadFilter()
948 filter.type = "lowpass"
949 filter.frequency.value = Math.max(200, 2000 - speed * 100)
950
951 source.connect(filter)
952 filter.connect(audioContextRef.current.destination)
953
954 const startTime = Math.max(
955 0,
956 Math.min(position, audioBufferRef.current.duration - 0.1)
957 )
958 source.start(0, startTime, 0.1)
959 scrubSourceRef.current = source
960 },
961 [enableAudioPlayback]
962 )
963
964 const playFromPosition = useCallback(
965 (position: number) => {
966 if (
967 !enableAudioPlayback ||
968 !audioBufferRef.current ||
969 !audioContextRef.current
970 )
971 return
972
973 if (sourceNodeRef.current) {
974 try {
975 sourceNodeRef.current.stop()
976 } catch {}
977 }
978
979 const source = audioContextRef.current.createBufferSource()
980 source.buffer = audioBufferRef.current
981 source.playbackRate.value = playbackRate
982 source.connect(audioContextRef.current.destination)
983
984 const startTime = Math.max(
985 0,
986 Math.min(position, audioBufferRef.current.duration)
987 )
988 source.start(0, startTime)
989 sourceNodeRef.current = source
990
991 playbackStartTimeRef.current =
992 audioContextRef.current.currentTime - startTime
993 setPlaybackPosition(startTime)
994
995 source.onended = () => {
996 setPlaybackPosition(null)
997 }
998 },
999 [enableAudioPlayback, playbackRate]
1000 )
1001
1002 useEffect(() => {
1003 if (playbackPosition === null || !audioBufferRef.current) return
1004
1005 let animationId: number
1006 const updatePlaybackVisual = () => {
1007 if (
1008 audioContextRef.current &&
1009 sourceNodeRef.current &&
1010 audioBufferRef.current
1011 ) {
1012 const elapsed =
1013 audioContextRef.current.currentTime - playbackStartTimeRef.current
1014 const currentPos = playbackPosition + elapsed * playbackRate
1015
1016 if (currentPos < audioBufferRef.current.duration) {
1017 const progressRatio = currentPos / audioBufferRef.current.duration
1018 const currentBarIndex = Math.floor(
1019 progressRatio * historyRef.current.length
1020 )
1021 const step = barWidth + barGap
1022
1023 const containerWidth =
1024 containerRef.current?.getBoundingClientRect().width || 0
1025 const viewBars = Math.floor(containerWidth / step)
1026 const targetOffset =
1027 -(currentBarIndex - (historyRef.current.length - viewBars)) * step
1028 const clampedOffset = Math.max(
1029 -(historyRef.current.length - viewBars) * step,
1030 Math.min(0, targetOffset)
1031 )
1032
1033 setDragOffset?.(clampedOffset)
1034 animationId = requestAnimationFrame(updatePlaybackVisual)
1035 } else {
1036 setPlaybackPosition(null)
1037 const step = barWidth + barGap
1038 const containerWidth =
1039 containerRef.current?.getBoundingClientRect().width || 0
1040 const viewBars = Math.floor(containerWidth / step)
1041 setDragOffset?.(-(historyRef.current.length - viewBars) * step)
1042 }
1043 }
1044 }
1045
1046 animationId = requestAnimationFrame(updatePlaybackVisual)
1047
1048 return () => {
1049 if (animationId) cancelAnimationFrame(animationId)
1050 }
1051 }, [
1052 playbackPosition,
1053 playbackRate,
1054 barWidth,
1055 baseBarHeight,
1056 barGap,
1057 setDragOffset,
1058 historyRef,
1059 ])
1060
1061 useEffect(() => {
1062 const canvas = canvasRef.current
1063 if (!canvas) return
1064 if (!active && historyRef.current.length === 0 && playbackPosition === null)
1065 return
1066
1067 const ctx = canvas.getContext("2d")
1068 if (!ctx) return
1069
1070 const animate = (currentTime: number) => {
1071 if (active && currentTime - lastUpdateRef.current > updateRate) {
1072 lastUpdateRef.current = currentTime
1073
1074 if (analyserRef.current) {
1075 const dataArray = new Uint8Array(
1076 analyserRef.current.frequencyBinCount
1077 )
1078 analyserRef.current.getByteFrequencyData(dataArray)
1079
1080 let sum = 0
1081 for (let i = 0; i < dataArray.length; i++) {
1082 sum += dataArray[i]
1083 }
1084 const average = (sum / dataArray.length / 255) * sensitivity
1085
1086 historyRef.current.push(Math.min(1, Math.max(0.05, average)))
1087
1088 if (historyRef.current.length > historySize) {
1089 historyRef.current.shift()
1090 }
1091 }
1092 }
1093
1094 const rect = canvas.getBoundingClientRect()
1095 ctx.clearRect(0, 0, rect.width, rect.height)
1096
1097 const computedBarColor =
1098 barColor ||
1099 getComputedStyle(canvas).getPropertyValue("--foreground") ||
1100 "#000"
1101
1102 const step = barWidth + barGap
1103 const barCount = Math.floor(rect.width / step)
1104 const centerY = rect.height / 2
1105
1106 const dataToRender = historyRef.current
1107
1108 if (dataToRender.length > 0) {
1109 const offsetInBars = Math.floor(dragOffset / step)
1110
1111 for (let i = 0; i < barCount; i++) {
1112 let dataIndex
1113
1114 if (active) {
1115 dataIndex = dataToRender.length - 1 - i
1116 } else {
1117 dataIndex = Math.max(
1118 0,
1119 Math.min(
1120 dataToRender.length - 1,
1121 dataToRender.length - 1 - i - Math.floor(offsetInBars)
1122 )
1123 )
1124 }
1125
1126 if (dataIndex >= 0 && dataIndex < dataToRender.length) {
1127 const value = dataToRender[dataIndex]
1128 if (value !== undefined) {
1129 const x = rect.width - (i + 1) * step
1130 const barHeight = Math.max(
1131 baseBarHeight,
1132 value * rect.height * 0.7
1133 )
1134 const y = centerY - barHeight / 2
1135
1136 ctx.fillStyle = computedBarColor
1137 ctx.globalAlpha = 0.3 + value * 0.7
1138
1139 if (barRadius > 0) {
1140 ctx.beginPath()
1141 ctx.roundRect(x, y, barWidth, barHeight, barRadius)
1142 ctx.fill()
1143 } else {
1144 ctx.fillRect(x, y, barWidth, barHeight)
1145 }
1146 }
1147 }
1148 }
1149 }
1150
1151 if (fadeEdges && fadeWidth > 0) {
1152 const gradient = ctx.createLinearGradient(0, 0, rect.width, 0)
1153 const fadePercent = Math.min(0.2, fadeWidth / rect.width)
1154
1155 gradient.addColorStop(0, "rgba(255,255,255,1)")
1156 gradient.addColorStop(fadePercent, "rgba(255,255,255,0)")
1157 gradient.addColorStop(1 - fadePercent, "rgba(255,255,255,0)")
1158 gradient.addColorStop(1, "rgba(255,255,255,1)")
1159
1160 ctx.globalCompositeOperation = "destination-out"
1161 ctx.fillStyle = gradient
1162 ctx.fillRect(0, 0, rect.width, rect.height)
1163 ctx.globalCompositeOperation = "source-over"
1164 }
1165
1166 ctx.globalAlpha = 1
1167
1168 animationRef.current = requestAnimationFrame(animate)
1169 }
1170
1171 if (active || historyRef.current.length > 0 || playbackPosition !== null) {
1172 animationRef.current = requestAnimationFrame(animate)
1173 }
1174
1175 return () => {
1176 if (animationRef.current) {
1177 cancelAnimationFrame(animationRef.current)
1178 }
1179 }
1180 }, [
1181 active,
1182 sensitivity,
1183 updateRate,
1184 historySize,
1185 barWidth,
1186 baseBarHeight,
1187 barGap,
1188 barRadius,
1189 barColor,
1190 fadeEdges,
1191 fadeWidth,
1192 dragOffset,
1193 playbackPosition,
1194 historyRef,
1195 ])
1196
1197 const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
1198 if (active || historyRef.current.length === 0) return
1199
1200 e.preventDefault()
1201 setIsDragging(true)
1202 dragStartXRef.current = e.clientX
1203 dragStartOffsetRef.current = dragOffset
1204 }
1205
1206 useEffect(() => {
1207 if (!isDragging) return
1208
1209 let lastScrubTime = 0
1210 let lastMouseX = dragStartXRef.current
1211 const handleMouseMove = (e: MouseEvent) => {
1212 const deltaX = e.clientX - dragStartXRef.current
1213 const newOffset = dragStartOffsetRef.current - deltaX * 0.5 // Reduce sensitivity
1214
1215 const step = barWidth + barGap
1216 const maxBars = historyRef.current.length
1217 const viewWidth = canvasRef.current?.getBoundingClientRect().width || 0
1218 const viewBars = Math.floor(viewWidth / step)
1219
1220 const maxOffset = Math.max(0, (maxBars - viewBars) * step)
1221 const minOffset = 0
1222 const clampedOffset = Math.max(minOffset, Math.min(maxOffset, newOffset))
1223
1224 setDragOffset?.(clampedOffset)
1225
1226 const now = Date.now()
1227 if (
1228 enableAudioPlayback &&
1229 audioBufferRef.current &&
1230 now - lastScrubTime > 50
1231 ) {
1232 lastScrubTime = now
1233 const offsetBars = Math.floor(clampedOffset / step)
1234 const rightmostBarIndex = Math.max(
1235 0,
1236 Math.min(maxBars - 1, maxBars - 1 - offsetBars)
1237 )
1238 const audioPosition =
1239 (rightmostBarIndex / maxBars) * audioBufferRef.current.duration
1240 const direction = e.clientX - lastMouseX
1241 lastMouseX = e.clientX
1242 playScrubSound(
1243 Math.max(
1244 0,
1245 Math.min(audioBufferRef.current.duration - 0.1, audioPosition)
1246 ),
1247 direction
1248 )
1249 }
1250 }
1251
1252 const handleMouseUp = () => {
1253 setIsDragging(false)
1254
1255 if (enableAudioPlayback && audioBufferRef.current) {
1256 const step = barWidth + barGap
1257 const maxBars = historyRef.current.length
1258 const offsetBars = Math.floor(dragOffset / step)
1259 const rightmostBarIndex = Math.max(
1260 0,
1261 Math.min(maxBars - 1, maxBars - 1 - offsetBars)
1262 )
1263 const audioPosition =
1264 (rightmostBarIndex / maxBars) * audioBufferRef.current.duration
1265 playFromPosition(
1266 Math.max(
1267 0,
1268 Math.min(audioBufferRef.current.duration - 0.1, audioPosition)
1269 )
1270 )
1271 }
1272
1273 if (scrubSourceRef.current) {
1274 try {
1275 scrubSourceRef.current.stop()
1276 } catch {}
1277 }
1278 }
1279
1280 document.addEventListener("mousemove", handleMouseMove)
1281 document.addEventListener("mouseup", handleMouseUp)
1282
1283 return () => {
1284 document.removeEventListener("mousemove", handleMouseMove)
1285 document.removeEventListener("mouseup", handleMouseUp)
1286 }
1287 }, [
1288 isDragging,
1289 barWidth,
1290 barGap,
1291 setDragOffset,
1292 dragOffset,
1293 enableAudioPlayback,
1294 playScrubSound,
1295 playFromPosition,
1296 historyRef,
1297 ])
1298
1299 return (
1300 <div
1301 className={cn(
1302 "relative flex items-center",
1303 !active && historyRef.current.length > 0 && "cursor-pointer",
1304 className
1305 )}
1306 onMouseDown={handleMouseDown}
1307 ref={containerRef}
1308 role={!active && historyRef.current.length > 0 ? "slider" : undefined}
1309 aria-label={
1310 !active && historyRef.current.length > 0
1311 ? "Drag to scrub through recording"
1312 : undefined
1313 }
1314 aria-valuenow={
1315 !active && historyRef.current.length > 0
1316 ? Math.abs(dragOffset)
1317 : undefined
1318 }
1319 aria-valuemin={!active && historyRef.current.length > 0 ? 0 : undefined}
1320 aria-valuemax={
1321 !active && historyRef.current.length > 0
1322 ? historyRef.current.length
1323 : undefined
1324 }
1325 tabIndex={!active && historyRef.current.length > 0 ? 0 : undefined}
1326 style={{ height: heightStyle }}
1327 {...props}
1328 >
1329 <canvas className="block h-full w-full" ref={canvasRef} />
1330 </div>
1331 )
1332}
1333
1334export type RecordingWaveformProps = Omit<
1335 WaveformProps,
1336 "data" | "onBarClick"
1337> & {
1338 recording?: boolean
1339 fftSize?: number
1340 smoothingTimeConstant?: number
1341 sensitivity?: number
1342 onError?: (error: Error) => void
1343 onRecordingComplete?: (data: number[]) => void
1344 updateRate?: number
1345 showHandle?: boolean
1346}
1347
1348export const RecordingWaveform = ({
1349 recording = false,
1350 fftSize = 256,
1351 smoothingTimeConstant = 0.8,
1352 sensitivity = 1,
1353 onError,
1354 onRecordingComplete,
1355 updateRate = 50,
1356 showHandle = true,
1357 barWidth = 3,
1358 barHeight: baseBarHeight = 4,
1359 barGap = 1,
1360 barRadius = 1,
1361 barColor,
1362 height = 128,
1363 className,
1364 ...props
1365}: RecordingWaveformProps) => {
1366 const [recordedData, setRecordedData] = useState<number[]>([])
1367 const [viewPosition, setViewPosition] = useState(1)
1368 const [isDragging, setIsDragging] = useState(false)
1369 const [isRecordingComplete, setIsRecordingComplete] = useState(false)
1370
1371 const canvasRef = useRef<HTMLCanvasElement>(null)
1372 const containerRef = useRef<HTMLDivElement>(null)
1373 const recordingDataRef = useRef<number[]>([])
1374 const analyserRef = useRef<AnalyserNode | null>(null)
1375 const audioContextRef = useRef<AudioContext | null>(null)
1376 const streamRef = useRef<MediaStream | null>(null)
1377 const animationRef = useRef<number>(0)
1378 const lastUpdateRef = useRef<number>(0)
1379
1380 const heightStyle = typeof height === "number" ? `${height}px` : height
1381
1382 useEffect(() => {
1383 const canvas = canvasRef.current
1384 const container = containerRef.current
1385 if (!canvas || !container) return
1386
1387 const resizeObserver = new ResizeObserver(() => {
1388 const rect = container.getBoundingClientRect()
1389 const dpr = window.devicePixelRatio || 1
1390
1391 canvas.width = rect.width * dpr
1392 canvas.height = rect.height * dpr
1393 canvas.style.width = `${rect.width}px`
1394 canvas.style.height = `${rect.height}px`
1395
1396 const ctx = canvas.getContext("2d")
1397 if (ctx) {
1398 ctx.scale(dpr, dpr)
1399 }
1400 })
1401
1402 resizeObserver.observe(container)
1403 return () => resizeObserver.disconnect()
1404 }, [])
1405
1406 useEffect(() => {
1407 if (!recording) {
1408 if (streamRef.current) {
1409 streamRef.current.getTracks().forEach((track) => track.stop())
1410 }
1411 if (
1412 audioContextRef.current &&
1413 audioContextRef.current.state !== "closed"
1414 ) {
1415 audioContextRef.current.close()
1416 }
1417
1418 if (recordingDataRef.current.length > 0) {
1419 setRecordedData([...recordingDataRef.current])
1420 setIsRecordingComplete(true)
1421 onRecordingComplete?.(recordingDataRef.current)
1422 }
1423 return
1424 }
1425
1426 setIsRecordingComplete(false)
1427 recordingDataRef.current = []
1428 setRecordedData([])
1429 setViewPosition(1)
1430
1431 const setupMicrophone = async () => {
1432 try {
1433 const stream = await navigator.mediaDevices.getUserMedia({
1434 audio: true,
1435 })
1436 streamRef.current = stream
1437
1438 const audioContext = new (window.AudioContext ||
1439 (window as unknown as { webkitAudioContext: typeof AudioContext })
1440 .webkitAudioContext)()
1441 const analyser = audioContext.createAnalyser()
1442 analyser.fftSize = fftSize
1443 analyser.smoothingTimeConstant = smoothingTimeConstant
1444
1445 const source = audioContext.createMediaStreamSource(stream)
1446 source.connect(analyser)
1447
1448 audioContextRef.current = audioContext
1449 analyserRef.current = analyser
1450 } catch (error) {
1451 onError?.(error as Error)
1452 }
1453 }
1454
1455 setupMicrophone()
1456
1457 return () => {
1458 if (streamRef.current) {
1459 streamRef.current.getTracks().forEach((track) => track.stop())
1460 }
1461 if (
1462 audioContextRef.current &&
1463 audioContextRef.current.state !== "closed"
1464 ) {
1465 audioContextRef.current.close()
1466 }
1467 }
1468 }, [recording, fftSize, smoothingTimeConstant, onError, onRecordingComplete])
1469
1470 useEffect(() => {
1471 const canvas = canvasRef.current
1472 if (!canvas) return
1473
1474 const ctx = canvas.getContext("2d")
1475 if (!ctx) return
1476
1477 const animate = (currentTime: number) => {
1478 if (recording && currentTime - lastUpdateRef.current > updateRate) {
1479 lastUpdateRef.current = currentTime
1480
1481 if (analyserRef.current) {
1482 const dataArray = new Uint8Array(
1483 analyserRef.current.frequencyBinCount
1484 )
1485 analyserRef.current.getByteFrequencyData(dataArray)
1486
1487 let sum = 0
1488 for (let i = 0; i < dataArray.length; i++) {
1489 sum += dataArray[i]
1490 }
1491 const average = (sum / dataArray.length / 255) * sensitivity
1492
1493 recordingDataRef.current.push(Math.min(1, Math.max(0.05, average)))
1494 }
1495 }
1496
1497 const rect = canvas.getBoundingClientRect()
1498 ctx.clearRect(0, 0, rect.width, rect.height)
1499
1500 const computedBarColor =
1501 barColor ||
1502 getComputedStyle(canvas).getPropertyValue("--foreground") ||
1503 "#000"
1504
1505 const dataToRender = recording ? recordingDataRef.current : recordedData
1506
1507 if (dataToRender.length > 0) {
1508 const step = barWidth + barGap
1509 const barsVisible = Math.floor(rect.width / step)
1510 const centerY = rect.height / 2
1511
1512 let startIndex = 0
1513 if (!recording && isRecordingComplete) {
1514 const totalBars = dataToRender.length
1515 if (totalBars > barsVisible) {
1516 startIndex = Math.floor((totalBars - barsVisible) * viewPosition)
1517 }
1518 } else if (recording) {
1519 startIndex = Math.max(0, dataToRender.length - barsVisible)
1520 }
1521
1522 for (
1523 let i = 0;
1524 i < barsVisible && startIndex + i < dataToRender.length;
1525 i++
1526 ) {
1527 const value = dataToRender[startIndex + i] || 0.1
1528 const x = i * step
1529 const barHeight = Math.max(baseBarHeight, value * rect.height * 0.7)
1530 const y = centerY - barHeight / 2
1531
1532 ctx.fillStyle = computedBarColor
1533 ctx.globalAlpha = 0.3 + value * 0.7
1534
1535 if (barRadius > 0) {
1536 ctx.beginPath()
1537 ctx.roundRect(x, y, barWidth, barHeight, barRadius)
1538 ctx.fill()
1539 } else {
1540 ctx.fillRect(x, y, barWidth, barHeight)
1541 }
1542 }
1543
1544 if (!recording && isRecordingComplete && showHandle) {
1545 const indicatorX = rect.width * viewPosition
1546
1547 ctx.strokeStyle = computedBarColor
1548 ctx.globalAlpha = 0.5
1549 ctx.lineWidth = 2
1550 ctx.beginPath()
1551 ctx.moveTo(indicatorX, 0)
1552 ctx.lineTo(indicatorX, rect.height)
1553 ctx.stroke()
1554 ctx.fillStyle = computedBarColor
1555 ctx.globalAlpha = 1
1556 ctx.beginPath()
1557 ctx.arc(indicatorX, centerY, 6, 0, Math.PI * 2)
1558 ctx.fill()
1559 }
1560 }
1561
1562 ctx.globalAlpha = 1
1563
1564 animationRef.current = requestAnimationFrame(animate)
1565 }
1566
1567 animationRef.current = requestAnimationFrame(animate)
1568
1569 return () => {
1570 if (animationRef.current) {
1571 cancelAnimationFrame(animationRef.current)
1572 }
1573 }
1574 }, [
1575 recording,
1576 recordedData,
1577 viewPosition,
1578 isRecordingComplete,
1579 sensitivity,
1580 updateRate,
1581 showHandle,
1582 barWidth,
1583 baseBarHeight,
1584 barGap,
1585 barRadius,
1586 barColor,
1587 ])
1588
1589 const handleScrub = useCallback(
1590 (clientX: number) => {
1591 const container = containerRef.current
1592 if (!container || recording || !isRecordingComplete) return
1593
1594 const rect = container.getBoundingClientRect()
1595 const x = Math.max(0, Math.min(clientX - rect.left, rect.width))
1596 const position = x / rect.width
1597
1598 setViewPosition(position)
1599 },
1600 [recording, isRecordingComplete]
1601 )
1602
1603 const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
1604 if (recording || !isRecordingComplete) return
1605
1606 e.preventDefault()
1607 setIsDragging(true)
1608 handleScrub(e.clientX)
1609 }
1610
1611 useEffect(() => {
1612 if (!isDragging) return
1613
1614 const handleMouseMove = (e: MouseEvent) => {
1615 handleScrub(e.clientX)
1616 }
1617
1618 const handleMouseUp = () => {
1619 setIsDragging(false)
1620 }
1621
1622 document.addEventListener("mousemove", handleMouseMove)
1623 document.addEventListener("mouseup", handleMouseUp)
1624
1625 return () => {
1626 document.removeEventListener("mousemove", handleMouseMove)
1627 document.removeEventListener("mouseup", handleMouseUp)
1628 }
1629 }, [isDragging, handleScrub])
1630
1631 return (
1632 <div
1633 aria-label={
1634 isRecordingComplete && !recording
1635 ? "Drag to scrub through recording"
1636 : undefined
1637 }
1638 aria-valuenow={
1639 isRecordingComplete && !recording ? viewPosition * 100 : undefined
1640 }
1641 aria-valuemin={isRecordingComplete && !recording ? 0 : undefined}
1642 aria-valuemax={isRecordingComplete && !recording ? 100 : undefined}
1643 className={cn(
1644 "relative flex items-center",
1645 isRecordingComplete && !recording && "cursor-pointer",
1646 className
1647 )}
1648 onMouseDown={handleMouseDown}
1649 ref={containerRef}
1650 role={isRecordingComplete && !recording ? "slider" : undefined}
1651 style={{ height: heightStyle }}
1652 tabIndex={isRecordingComplete && !recording ? 0 : undefined}
1653 {...props}
1654 >
1655 <canvas className="block h-full w-full" ref={canvasRef} />
1656 </div>
1657 )
1658}
1659