-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.tsx
228 lines (195 loc) · 5.83 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/**
* A React component for wavesurfer.js
*
* Usage:
*
* import WavesurferPlayer from '@wavesurfer/react'
*
* <WavesurferPlayer
* url="/my-server/audio.ogg"
* waveColor="purple"
* height={100}
* onReady={(wavesurfer) => console.log('Ready!', wavesurfer)}
* />
*/
import { useState, useMemo, useEffect, useRef, memo, type ReactElement, type RefObject } from 'react'
import WaveSurfer, { type WaveSurferEvents, type WaveSurferOptions } from 'wavesurfer.js'
type WavesurferEventHandler<T extends unknown[]> = (wavesurfer: WaveSurfer, ...args: T) => void
type OnWavesurferEvents = {
[K in keyof WaveSurferEvents as `on${Capitalize<K>}`]?: WavesurferEventHandler<WaveSurferEvents[K]>
}
type PartialWavesurferOptions = Omit<WaveSurferOptions, 'container'>
/**
* Props for the Wavesurfer component
* @public
*/
export type WavesurferProps = PartialWavesurferOptions & OnWavesurferEvents
/**
* Use wavesurfer instance
*/
function useWavesurferInstance(
containerRef: RefObject<HTMLElement>,
options: Partial<WaveSurferOptions>,
): WaveSurfer | null {
const [wavesurfer, setWavesurfer] = useState<WaveSurfer | null>(null)
// Flatten options object to an array of keys and values to compare them deeply in the hook deps
const flatOptions = useMemo(() => Object.entries(options).flat(), [options])
// Create a wavesurfer instance
useEffect(() => {
if (!containerRef.current) return
const ws = WaveSurfer.create({
...options,
container: containerRef.current,
})
setWavesurfer(ws)
return () => {
ws.destroy()
}
}, [containerRef, ...flatOptions])
return wavesurfer
}
/**
* Use wavesurfer state
*/
function useWavesurferState(wavesurfer: WaveSurfer | null): {
isReady: boolean
isPlaying: boolean
currentTime: number
} {
const [isReady, setIsReady] = useState<boolean>(false)
const [isPlaying, setIsPlaying] = useState<boolean>(false)
const [currentTime, setCurrentTime] = useState<number>(0)
useEffect(() => {
if (!wavesurfer) return
const unsubscribeFns = [
wavesurfer.on('load', () => {
setIsReady(false)
setIsPlaying(false)
setCurrentTime(0)
}),
wavesurfer.on('ready', () => {
setIsReady(true)
setIsPlaying(false)
setCurrentTime(0)
}),
wavesurfer.on('play', () => {
setIsPlaying(true)
}),
wavesurfer.on('pause', () => {
setIsPlaying(false)
}),
wavesurfer.on('timeupdate', () => {
setCurrentTime(wavesurfer.getCurrentTime())
}),
wavesurfer.on('destroy', () => {
setIsReady(false)
setIsPlaying(false)
}),
]
return () => {
unsubscribeFns.forEach((fn) => fn())
}
}, [wavesurfer])
return useMemo(
() => ({
isReady,
isPlaying,
currentTime,
}),
[isPlaying, currentTime, isReady],
)
}
const EVENT_PROP_RE = /^on([A-Z])/
const isEventProp = (key: string) => EVENT_PROP_RE.test(key)
const getEventName = (key: string) => key.replace(EVENT_PROP_RE, (_, $1) => $1.toLowerCase()) as keyof WaveSurferEvents
/**
* Parse props into wavesurfer options and events
*/
function useWavesurferProps(props: WavesurferProps): [PartialWavesurferOptions, OnWavesurferEvents] {
// Props starting with `on` are wavesurfer events, e.g. `onReady`
// The rest of the props are wavesurfer options
return useMemo<[PartialWavesurferOptions, OnWavesurferEvents]>(() => {
const allOptions = { ...props }
const allEvents = { ...props }
for (const key in allOptions) {
if (isEventProp(key)) {
delete allOptions[key as keyof WavesurferProps]
} else {
delete allEvents[key as keyof WavesurferProps]
}
}
return [allOptions, allEvents]
}, [props])
}
/**
* Subscribe to wavesurfer events
*/
function useWavesurferEvents(wavesurfer: WaveSurfer | null, events: OnWavesurferEvents) {
const flatEvents = useMemo(() => Object.entries(events).flat(), [events])
// Subscribe to events
useEffect(() => {
if (!wavesurfer) return
const eventEntries = Object.entries(events)
if (!eventEntries.length) return
const unsubscribeFns = eventEntries.map(([name, handler]) => {
const event = getEventName(name)
return wavesurfer.on(event, (...args) =>
(handler as WavesurferEventHandler<WaveSurferEvents[typeof event]>)(wavesurfer, ...args),
)
})
return () => {
unsubscribeFns.forEach((fn) => fn())
}
}, [wavesurfer, ...flatEvents])
}
/**
* Wavesurfer player component
* @see https://wavesurfer.xyz/docs/modules/wavesurfer
* @public
*/
const WavesurferPlayer = memo((props: WavesurferProps): ReactElement => {
const containerRef = useRef<HTMLDivElement | null>(null)
const [options, events] = useWavesurferProps(props)
const wavesurfer = useWavesurferInstance(containerRef, options)
useWavesurferEvents(wavesurfer, events)
// Create a container div
return <div ref={containerRef} />
})
/**
* @public
*/
export default WavesurferPlayer
/**
* React hook for wavesurfer.js
*
* ```
* import { useWavesurfer } from '@wavesurfer/react'
*
* const App = () => {
* const containerRef = useRef<HTMLDivElement | null>(null)
*
* const { wavesurfer, isReady, isPlaying, currentTime } = useWavesurfer({
* container: containerRef,
* url: '/my-server/audio.ogg',
* waveColor: 'purple',
* height: 100',
* })
*
* return <div ref={containerRef} />
* }
* ```
*
* @public
*/
export function useWavesurfer({
container,
...options
}: Omit<WaveSurferOptions, 'container'> & { container: RefObject<HTMLElement> }): ReturnType<
typeof useWavesurferState
> & {
wavesurfer: ReturnType<typeof useWavesurferInstance>
} {
const wavesurfer = useWavesurferInstance(container, options)
const state = useWavesurferState(wavesurfer)
return useMemo(() => ({ ...state, wavesurfer }), [state, wavesurfer])
}