/
index.ts
501 lines (425 loc) · 13.6 KB
/
index.ts
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import { watch, ref, unref, watchEffect } from 'vue-demi'
import { isObject, MaybeRef, isString, ignorableWatch, isNumber, tryOnUnmounted, Fn } from '@vueuse/shared'
import { useEventListener } from '../useEventListener'
import { ConfigurableDocument, defaultDocument } from '../_configurable'
/**
* Many of the jsdoc definitions here are modified version of the
* documentation from MDN(https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement)
*/
export interface UseMediaSource {
/**
* The source url for the media
*/
src: string
/**
* The media codec type
*/
type?: string
}
export interface UseMediaTextTrackSource {
/**
* Indicates that the track should be enabled unless the user's preferences indicate
* that another track is more appropriate
*/
default?: boolean
/**
* How the text track is meant to be used. If omitted the default kind is subtitles.
*/
kind: TextTrackKind
/**
* A user-readable title of the text track which is used by the browser
* when listing available text tracks.
*/
label: string
/**
* Address of the track (.vtt file). Must be a valid URL. This attribute
* must be specified and its URL value must have the same origin as the document
*/
src: string
/**
* Language of the track text data. It must be a valid BCP 47 language tag.
* If the kind attribute is set to subtitles, then srclang must be defined.
*/
srcLang: string
}
interface UseMediaControlsOptions extends ConfigurableDocument {
/**
* The source for the media, may either be a string, a `UseMediaSource` object, or a list
* of `UseMediaSource` objects.
*/
src?: MaybeRef<string | UseMediaSource | UseMediaSource[]>
/**
* A URL for an image to be shown while the media is downloading. If this attribute
* isn't specified, nothing is displayed until the first frame is available,
* then the first frame is shown as the poster frame.
*/
poster?: MaybeRef<string>
/**
* Indicates that the media automatically begins to play back as soon as it
* can do so without stopping to finish loading the data.
*
* @default false
*/
autoplay?: MaybeRef<boolean>
/**
* Indicates that the media is to be played "inline", that is within the
* element's playback area. Note that the absence of this attribute does
* not imply that the media will always be played in fullscreen.
*
* @default auto
*/
preload?: MaybeRef<'auto' | 'metadata' | 'none' >
/**
* If specified, the browser will automatically seek back to the start
* upon reaching the end of the media.
*
* @default false
*/
loop?: MaybeRef<boolean>
/**
* If true, the browser will offer controls to allow the user to control
* media playback, including volume, seeking, and pause/resume playback.
*
* @default false
*/
controls?: MaybeRef<boolean>
/**
* If true, the audio will be initially silenced. Its default value is false,
* meaning that the audio will be played when the media is played.
*
* @default false
*/
muted?: MaybeRef<boolean>
/**
* Indicates that the video is to be played "inline", that is within the element's
* playback area. Note that the absence of this attribute does not imply
* that the video will always be played in fullscreen.
*
* @default false
*/
playsinline?: MaybeRef<boolean>
/**
* A Boolean attribute which if true indicates that the element should automatically
* toggle picture-in-picture mode when the user switches back and forth between
* this document and another document or application.
*
* @default false
*/
autoPictureInPicture?: MaybeRef<boolean>
/**
* A list of text tracks for the media
*/
tracks?: MaybeRef<UseMediaTextTrackSource[]>
}
export interface UseMediaTextTrack {
/**
* The index of the text track
*/
id: number
/**
* The text track label
*/
label: string
/**
* Language of the track text data. It must be a valid BCP 47 language tag.
* If the kind attribute is set to subtitles, then srclang must be defined.
*/
language: string
/**
* Specifies the display mode of the text track, either `disabled`,
* `hidden`, or `showing`
*/
mode: TextTrackMode
/**
* How the text track is meant to be used. If omitted the default kind is subtitles.
*/
kind: TextTrackKind
/**
* Indicates the track's in-band metadata track dispatch type.
*/
inBandMetadataTrackDispatchType: string
/**
* A list of text track cues
*/
cues: TextTrackCueList | null
/**
* A list of active text track cues
*/
activeCues: TextTrackCueList | null
}
/**
* Automatically check if the ref exists and if it does run the cb fn
*/
function usingElRef<T = any>(source: MaybeRef<any>, cb: (el: T) => void) {
if (unref(source))
cb(unref(source))
}
/**
* Converts a TimeRange object to an array
*/
function timeRangeToArray(timeRanges: TimeRanges) {
let ranges: [number, number][] = []
for (let i = 0; i < timeRanges.length; ++i)
ranges = [...ranges, [timeRanges.start(i), timeRanges.end(i)]]
return ranges
}
/**
* Converts a TextTrackList object to an array of `UseMediaTextTrack`
*/
function tracksToArray(tracks: TextTrackList): UseMediaTextTrack[] {
return Array.from(tracks)
.map(({ label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType }, id) =>
({ id, label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType }))
}
const defaultOptions: UseMediaControlsOptions = {
src: '',
poster: '',
autoplay: false,
preload: 'auto',
loop: false,
controls: false,
muted: false,
playsinline: false,
autoPictureInPicture: false,
tracks: [],
}
export function useMediaControls(target: MaybeRef<HTMLMediaElement | null | undefined>, options: UseMediaControlsOptions = {}) {
options = {
...defaultOptions,
...options,
}
const {
document = defaultDocument,
} = options
const currentTime = ref(0)
const duration = ref(0)
const seeking = ref(false)
const buffering = ref(false)
const volume = ref(1)
const waiting = ref(false)
const ended = ref(false)
const playing = ref(false)
const rate = ref(1)
const stalled = ref(false)
const buffered = ref<[number, number][]>([])
const tracks = ref<UseMediaTextTrack[]>([])
const selectedTrack = ref<number>(-1)
const isPictureInPicture = ref(false)
const supportsPictureInPicture = document && 'pictureInPictureEnabled' in document
/**
* Disables the specified track. If no track is specified then
* all tracks will be disabled
*
* @param track The id of the track to disable
*/
const disableTrack = (track?: number | UseMediaTextTrack) => {
usingElRef<HTMLMediaElement>(target, (el) => {
if (track) {
const id = isNumber(track) ? track : track.id
el.textTracks[id].mode = 'disabled'
}
else {
for (let i = 0; i < el.textTracks.length; ++i)
el.textTracks[i].mode = 'disabled'
}
selectedTrack.value = -1
})
}
/**
* Enables the specified track and disables the
* other tracks unless otherwise specified
*
* @param track The track of the id of the track to enable
* @param disableTracks Disable all other tracks
*/
const enableTrack = (track: number | UseMediaTextTrack, disableTracks = true) => {
usingElRef<HTMLMediaElement>(target, (el) => {
const id = isNumber(track) ? track : track.id
if (disableTracks)
disableTrack()
el.textTracks[id].mode = 'showing'
selectedTrack.value = id
})
}
/**
* Toggle picture in picture mode for the player.
*/
const togglePictureInPicture = () => {
return new Promise((resolve, reject) => {
usingElRef<HTMLVideoElement>(target, async(el) => {
if (supportsPictureInPicture) {
if (!isPictureInPicture.value) {
(el as any).requestPictureInPicture()
.then(resolve)
.catch(reject)
}
else {
(document as any).exitPictureInPicture()
.then(resolve)
.catch(reject)
}
}
})
})
}
// Apply Options
watchEffect(() => {
const el = unref(target)
if (!el)
return
el.loop = unref(options.loop)!
el.controls = unref(options.controls)!
el.muted = unref(options.muted)!
el.preload = unref(options.preload)!
el.autoplay = unref(options.autoplay)!
el.volume = unref(volume)!
;(el as HTMLVideoElement).playsInline = unref(options.playsinline)!
;(el as HTMLVideoElement).poster = unref(options.poster) || ''
})
/**
* This will automatically inject sources to the media element. The sources will be
* appended as children to the media element as `<source>` elements.
*/
watchEffect(() => {
if (!document)
return
const el = unref(target)
if (!el)
return
const src = unref(options.src)
let sources: UseMediaSource[] = []
if (!src)
return
// Merge sources into an array
if (isString(src))
sources = [{ src }]
else if (Array.isArray(src))
sources = src
else if (isObject(src))
sources = [src]
// Clear the sources
el.querySelectorAll('source').forEach(e => e.remove())
// Add new sources
sources.forEach(({ src, type }) => {
const source = document.createElement('source')
source.setAttribute('src', src)
source.setAttribute('type', type || '')
el.appendChild(source)
})
// Finally, load the new sources.
el.load()
})
/**
* Watch volume and change player volume when volume prop changes
*/
watch(volume, (vol) => {
const el = unref(target)
if (!el)
return
el.volume = vol
})
/**
* Load Tracks
*/
watchEffect(() => {
if (!document)
return
const textTracks = unref(options.tracks)
const el = unref(target)
if (!textTracks || !textTracks.length || !el)
return
/**
* The MediaAPI provides an API for adding text tracks, but they don't currently
* have an API for removing text tracks, so instead we will just create and remove
* the tracks manually using the HTML api.
*/
el.querySelectorAll('track').forEach(e => e.remove())
textTracks.forEach(({ default: isDefault, kind, label, src, srcLang }, i) => {
const track = document.createElement('track')
track.default = isDefault || false
track.kind = kind
track.label = label
track.src = src
track.srclang = srcLang
if (track.default)
selectedTrack.value = i
el.appendChild(track)
})
})
/**
* This will allow us to update the current time from the timeupdate event
* without setting the medias current position, but if the user changes the
* current time via the ref, then the media will seek.
*
* If we did not use an ignorable watch, then the current time update from
* the timeupdate event would cause the media to stutter.
*/
const { ignoreUpdates: ignoreCurrentTimeUpdates } = ignorableWatch(currentTime, (time) => {
const el = unref(target)
if (!el)
return
el.currentTime = time
})
/**
* Using an ignorable watch so we can control the play state using a ref and not
* a function
*/
const { ignoreUpdates: ignorePlayingUpdates } = ignorableWatch(playing, (isPlaying) => {
const el = unref(target)
if (!el)
return
isPlaying ? el.play() : el.pause()
})
useEventListener(target, 'timeupdate', () => ignoreCurrentTimeUpdates(() => currentTime.value = (unref(target))!.currentTime))
useEventListener(target, 'durationchange', () => duration.value = (unref(target))!.duration)
useEventListener(target, 'progress', () => buffered.value = timeRangeToArray((unref(target))!.buffered))
useEventListener(target, 'seeking', () => seeking.value = true)
useEventListener(target, 'seeked', () => seeking.value = false)
useEventListener(target, 'waiting', () => waiting.value = true)
useEventListener(target, 'playing', () => waiting.value = false)
useEventListener(target, 'ratechange', () => rate.value = (unref(target))!.playbackRate)
useEventListener(target, 'stalled', () => stalled.value = true)
useEventListener(target, 'ended', () => ended.value = true)
useEventListener(target, 'pause', () => ignorePlayingUpdates(() => playing.value = false))
useEventListener(target, 'play', () => ignorePlayingUpdates(() => playing.value = true))
useEventListener(target, 'enterpictureinpicture', () => isPictureInPicture.value = true)
useEventListener(target, 'leavepictureinpicture', () => isPictureInPicture.value = false)
/**
* The following listeners need to listen to a nested
* object on the target, so we will have to use a nested
* watch and manually remove the listeners
*/
const listeners: Fn[] = []
const stop = watch([target], () => {
const el = unref(target)
if (!el)
return
stop()
listeners[0] = useEventListener(el.textTracks, 'addtrack', () => tracks.value = tracksToArray(el.textTracks))
listeners[1] = useEventListener(el.textTracks, 'removetrack', () => tracks.value = tracksToArray(el.textTracks))
listeners[2] = useEventListener(el.textTracks, 'change', () => tracks.value = tracksToArray(el.textTracks))
})
// Remove text track listeners
tryOnUnmounted(() => listeners.forEach(listener => listener()))
return {
currentTime,
duration,
buffering,
waiting,
seeking,
ended,
stalled,
buffered,
playing,
volume,
// Tracks
tracks,
selectedTrack,
enableTrack,
disableTrack,
// Picture in Picture
supportsPictureInPicture,
togglePictureInPicture,
isPictureInPicture,
}
}