Line data Source code
1 : import { useTimeoutFn } from '@vueuse/core'
2 : import { nextTick, readonly, ref, toValue, watch } from 'vue'
3 : import type { MaybeRefOrGetter } from 'vue'
4 :
5 : export type MediaSrcStatus = 'idle' | 'loading' | 'retrying' | 'failed'
6 :
7 2355 : const RETRY_DELAYS_MS = [500, 1000, 2000, 4000, 8000] as const
8 :
9 88 : export function useRetryableMediaSrc(
10 : source: MaybeRefOrGetter<string | undefined>
11 : ) {
12 88 : const src = ref<string | undefined>()
13 88 : const status = ref<MediaSrcStatus>('idle')
14 88 : let retriesUsed = 0
15 88 : let generation = 0
16 88 : const nextDelay = ref<number>(RETRY_DELAYS_MS[0])
17 :
18 88 : const reload = async () => {
19 1 : const gen = ++generation
20 1 : src.value = undefined
21 1 : await nextTick()
22 1 : if (gen !== generation) return
23 1 : src.value = toValue(source)
24 1 : status.value = 'loading'
25 : }
26 :
27 88 : const { start, stop } = useTimeoutFn(reload, nextDelay, {
28 : immediate: false
29 : })
30 :
31 88 : const bind = (url: string | undefined) => {
32 88 : stop()
33 88 : generation++
34 88 : retriesUsed = 0
35 88 : src.value = url
36 88 : status.value = url ? 'loading' : 'idle'
37 : }
38 :
39 88 : const onError = () => {
40 3 : if (status.value !== 'loading') return
41 :
42 3 : if (retriesUsed >= RETRY_DELAYS_MS.length) {
43 0 : status.value = 'failed'
44 0 : return
45 : }
46 :
47 3 : nextDelay.value = RETRY_DELAYS_MS[retriesUsed]
48 3 : retriesUsed++
49 3 : status.value = 'retrying'
50 3 : start()
51 : }
52 :
53 88 : const retry = () => {
54 0 : if (status.value === 'idle') return
55 :
56 0 : stop()
57 0 : retriesUsed = 0
58 0 : status.value = 'retrying'
59 0 : void reload()
60 : }
61 :
62 88 : watch(() => toValue(source), bind, { immediate: true, flush: 'sync' })
63 :
64 88 : return {
65 : src: readonly(src),
66 : status: readonly(status),
67 : onError,
68 : retry
69 : }
70 : }
|