Skip to content

Commit

Permalink
fix(Avatar): support referrer policy in AvatarImage.vue (#1477)
Browse files Browse the repository at this point in the history
(from radix-ui)
  • Loading branch information
sadeghbarati authored Dec 4, 2024
1 parent 4a0ad49 commit a2d2b1a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
8 changes: 5 additions & 3 deletions packages/radix-vue/src/Avatar/AvatarImage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,24 @@ export type AvatarImageEmits = {
}
export interface AvatarImageProps extends PrimitiveProps {
src: string
referrerPolicy?: ImgHTMLAttributes['referrerpolicy']
}
</script>

<script setup lang="ts">
import { toRefs, watch } from 'vue'
import { type ImgHTMLAttributes, toRefs, watch } from 'vue'
import { Primitive } from '../Primitive'
import { injectAvatarRootContext } from './AvatarRoot.vue'
import { useImageLoadingStatus } from './utils'
const props = withDefaults(defineProps<AvatarImageProps>(), { as: 'img' })
const emits = defineEmits<AvatarImageEmits>()
const { src } = toRefs(props)
const { src, referrerPolicy } = toRefs(props)
useForwardExpose()
const rootContext = injectAvatarRootContext()
const imageLoadingStatus = useImageLoadingStatus(src)
const imageLoadingStatus = useImageLoadingStatus(src, referrerPolicy)
watch(
imageLoadingStatus,
Expand All @@ -48,6 +49,7 @@ watch(
:as-child="asChild"
:as="as"
:src="src"
:referrer-policy="referrerPolicy"
>
<slot />
</Primitive>
Expand Down
13 changes: 8 additions & 5 deletions packages/radix-vue/src/Avatar/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { type Ref, onMounted, onUnmounted, ref, watch } from 'vue'
import { type ImgHTMLAttributes, type Ref, onMounted, onUnmounted, ref, watch } from 'vue'

export type ImageLoadingStatus = 'idle' | 'loading' | 'loaded' | 'error'

export function useImageLoadingStatus(src: Ref<string>) {
export function useImageLoadingStatus(src: Ref<string>, referrerPolicy?: Ref<ImgHTMLAttributes['referrerpolicy']>) {
const loadingStatus = ref<ImageLoadingStatus>('idle')
const isMounted = ref(false)

Expand All @@ -14,16 +14,19 @@ export function useImageLoadingStatus(src: Ref<string>) {
onMounted(() => {
isMounted.value = true

watch(src, (value) => {
if (!value) {
watch([() => src.value, () => referrerPolicy?.value], ([src, referrer]) => {
if (!src) {
loadingStatus.value = 'error'
}
else {
const image = new window.Image()
loadingStatus.value = 'loading'
image.onload = updateStatus('loaded')
image.onerror = updateStatus('error')
image.src = value
image.src = src
if (referrer) {
image.referrerPolicy = referrer
}
}
}, { immediate: true })
})
Expand Down

0 comments on commit a2d2b1a

Please sign in to comment.