Skip to content

Commit

Permalink
feat(Avatar): use NuxtImg component when available
Browse files Browse the repository at this point in the history
Resolves #2078
  • Loading branch information
benjamincanac committed Nov 7, 2024
1 parent 0454124 commit f1a14dd
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
4 changes: 4 additions & 0 deletions docs/content/3.components/avatar.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ links:

## Usage

::tip
The Avatar uses the `NuxtImg` component when `@nuxt/image` is installed, falling back to `img` otherwise.
::

### Src

Use the `src` prop to set the image URL. You can pass any property from HTML `<img>` element such as `alt`, `loading`, etc.
Expand Down
11 changes: 6 additions & 5 deletions src/runtime/components/Avatar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ type AvatarVariants = VariantProps<typeof avatar>
export interface AvatarProps extends Pick<AvatarFallbackProps, 'delayMs'> {
/**
* The element or component this component should render as.
* @defaultValue 'img'
* @defaultValue 'span'
*/
as?: string | object
as?: any
src?: string
alt?: string
icon?: string
Expand All @@ -36,10 +36,11 @@ import { AvatarRoot, AvatarImage, AvatarFallback, useForwardProps } from 'radix-
import { reactivePick } from '@vueuse/core'
import { useAvatarGroup } from '../composables/useAvatarGroup'
import UIcon from './Icon.vue'
import ImageComponent from '#build/ui-image-component'
defineOptions({ inheritAttrs: false })
const props = defineProps<AvatarProps>()
const props = withDefaults(defineProps<AvatarProps>(), { as: 'span' })
const fallbackProps = useForwardProps(reactivePick(props, 'delayMs'))
Expand All @@ -54,10 +55,10 @@ const ui = computed(() => avatar({
</script>

<template>
<AvatarRoot :class="ui.root({ class: [props.class, props.ui?.root] })">
<AvatarRoot :as="as" :class="ui.root({ class: [props.class, props.ui?.root] })">
<AvatarImage
v-if="src"
:as="as"
:as="ImageComponent"
:src="src"
:alt="alt"
v-bind="$attrs"
Expand Down
10 changes: 10 additions & 0 deletions src/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ export {}
`
})

templates.push({
filename: 'ui-image-component.ts',
write: true,
getContents: ({ app }) => {
const image = app?.components?.find(c => c.pascalName === 'NuxtImg' && !c.filePath.includes('nuxt/dist/app'))

return image ? `export { default } from "${image.filePath}"` : 'export default "img"'
}
})

return templates
}

Expand Down

0 comments on commit f1a14dd

Please sign in to comment.