-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathutils.ts
41 lines (32 loc) · 1.01 KB
/
utils.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
import type { MaybeRefOrGetter } from 'vue'
import type { AvatarImageProps } from './AvatarImage.ts'
import type { ImageLoadingStatus } from './AvatarRoot.ts'
import { isClient } from '@vueuse/core'
import { onWatcherCleanup, shallowRef, toValue, watchEffect } from 'vue'
export function useImageLoadingStatus(src: MaybeRefOrGetter<AvatarImageProps['src']>) {
const loadingStatus = shallowRef<ImageLoadingStatus>('idle')
if (!isClient)
return loadingStatus
watchEffect(() => {
const value = toValue(src)
if (!value) {
loadingStatus.value = 'error'
return
}
let isMounted = true
const image = new window.Image()
const updateStatus = (status: ImageLoadingStatus) => () => {
if (!isMounted)
return
loadingStatus.value = status
}
loadingStatus.value = 'loading'
image.onload = updateStatus('loaded')
image.onerror = updateStatus('error')
image.src = value
onWatcherCleanup(() => {
isMounted = false
})
})
return loadingStatus
}