Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/2.usage/2.nuxt-picture.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,35 @@ Format used for fallback. Default is conditional:
- If original format supports transparency (`png`, `webp`, and `gif`), `png` is used for fallback
- Otherwise `jpeg` is used for fallback

### `placeholder`

Display a placeholder image before the actual image is fully loaded. It accepts the same values as the [`placeholder` prop of `<NuxtImg>`](/modules/image/usage/nuxt-img#placeholder).

```vue
<!-- Automatically generate a placeholder based on the original image -->
<NuxtPicture src="/nuxt.png" placeholder />

<!-- Set a width, height, quality & blur for the automatically generated placeholder -->
<NuxtPicture src="/nuxt.png" :placeholder="[50, 25, 75, 5]" />

<!-- Provide your own image -->
<NuxtPicture src="/nuxt.png" placeholder="./placeholder.png" />
```

While the placeholder is displayed, `<NuxtPicture>` renders a plain `<img>` without any `<source>`. The real image is loaded in the background using the same `<source>` candidates, and once it is ready the `<picture>` is rendered with all its sources. A generated placeholder uses the [`legacyFormat`](#legacyformat). Placeholders are ignored for SVG images.

### `placeholderClass`

When using a placeholder, you can use `placeholderClass` to apply a class to the underlying `<img>` element while the placeholder is being rendered.

```vue
<NuxtPicture
src="/nuxt.png"
placeholder
placeholder-class="blurred"
/>
```

### `imgAttrs`

Allows you to set additional HTML-attributes on the `img` element.
Expand Down
23 changes: 6 additions & 17 deletions src/runtime/components/NuxtImg.vue
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,15 @@ import type { ImgHTMLAttributes } from 'vue'
import { useImage } from '../composables'
import { prerenderStaticImages } from '../utils/prerender'
import { markFeatureUsage } from '../utils/performance'
import { useImageProps } from '../utils/props'
import type { BaseImageProps } from '../utils/props'
import { resolvePlaceholder, useImageProps } from '../utils/props'
import type { BaseImageProps, PlaceholderProp } from '../utils/props'
import type { ProviderDefaults, ConfiguredImageProviders } from '@nuxt/image'

import { useHead, useNuxtApp, useRequestEvent } from '#imports'

export interface ImageProps<Provider extends keyof ConfiguredImageProviders> extends BaseImageProps<Provider> {
custom?: boolean
placeholder?: boolean | string | number | [w: number, h: number, q?: number, b?: number]
placeholder?: PlaceholderProp
placeholderClass?: string
}

Expand Down Expand Up @@ -72,26 +72,15 @@ const placeholder = computed(() => {
return false
}

const placeholder = props.placeholder === '' ? [10, 10] : props.placeholder
const placeholder = resolvePlaceholder(props.placeholder)

if (!placeholder) {
return false
}

if (typeof placeholder === 'string') {
if (typeof placeholder !== 'object') {
return placeholder
}

const [width = 10, height = width, quality = 50, blur = 3] = Array.isArray(placeholder)
? placeholder
: typeof placeholder === 'number' ? [placeholder] : []

return $img(props.src!, {
...imageModifiers.value,
width,
height,
quality,
blur,
...placeholder,
}, providerOptions.value)
})

Expand Down
89 changes: 81 additions & 8 deletions src/runtime/components/NuxtPicture.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,21 @@
<picture v-bind="attrs.picture">
<template v-for="(source, index) of sources">
<source
v-if="index + 1 < sources.length"
v-if="index + 1 < sources.length && !placeholder"
:key="source.src"
:type="source.type"
:sizes="source.sizes"
:srcset="source.srcset"
>
<img
v-else
v-else-if="index + 1 === sources.length"
ref="imgEl"
:key="'last' + source.src"
:class="placeholder ? placeholderClass : undefined"
v-bind="attrs.img"
:src="source.src"
:sizes="source.sizes"
:srcset="source.srcset"
:src="placeholder || source.src"
:sizes="placeholder ? undefined : source.sizes"
:srcset="placeholder ? undefined : source.srcset"
>
</template>
</picture>
Expand All @@ -25,13 +26,13 @@
import type { SerializableHead } from '@unhead/vue/types'
import type { ImgHTMLAttributes } from 'vue'

import { computed, onMounted, useAttrs, useTemplateRef } from 'vue'
import { computed, onMounted, ref, useAttrs, useTemplateRef } from 'vue'

import { prerenderStaticImages } from '../utils/prerender'
import { markFeatureUsage } from '../utils/performance'
import { useImage } from '../composables'
import { useImageProps } from '../utils/props'
import type { BaseImageProps } from '../utils/props'
import { resolvePlaceholder, useImageProps } from '../utils/props'
import type { BaseImageProps, PlaceholderProp } from '../utils/props'
import type { DataAttributes } from '../types'
import type { ConfiguredImageProviders, ProviderDefaults } from '@nuxt/image'

Expand All @@ -40,6 +41,8 @@ import { useHead, useNuxtApp, useRequestEvent } from '#imports'
export interface PictureProps<Provider extends keyof ConfiguredImageProviders> extends BaseImageProps<Provider> {
legacyFormat?: string
imgAttrs?: ImgHTMLAttributes & DataAttributes
placeholder?: PlaceholderProp
placeholderClass?: string
}

defineOptions({ inheritAttrs: false })
Expand Down Expand Up @@ -119,6 +122,29 @@ const sources = computed<Source[]>(() => {
})
})

const placeholderLoaded = ref(false)

// The placeholder is rendered as a plain `<img>` (without any `<source>`) until
// the real image has been loaded.
const placeholder = computed(() => {
// SVGs are not converted into multiple formats, so there is nothing to wait for
if (placeholderLoaded.value || !sources.value.some(source => source.type)) {
return false
}

const placeholder = resolvePlaceholder(props.placeholder)

if (typeof placeholder !== 'object') {
return placeholder
}

return $img(props.src!, {
...imageModifiers.value,
...placeholder,
format: legacyFormat.value,
}, providerOptions.value)
})

if (import.meta.server && props.preload) {
useHead({ link: () => {
const firstSource = sources.value[0]
Expand Down Expand Up @@ -146,13 +172,60 @@ if (import.meta.server && import.meta.prerender) {
for (const src of sources.value) {
prerenderStaticImages(src.src, src.srcset, useRequestEvent())
}
if (placeholder.value) {
prerenderStaticImages(placeholder.value, undefined, useRequestEvent())
}
}

const nuxtApp = useNuxtApp()
const initialLoad = nuxtApp.isHydrating

const imgEl = useTemplateRef('imgEl')

function setAttributes(el: Element, attrs: Record<string, string | undefined>) {
for (const key in attrs) {
if (attrs[key]) {
el.setAttribute(key, attrs[key])
}
}
}

// Loads the real image off-screen, using the same `<source>` candidates as the
// final markup so the browser picks the format and size it would pick anyway.
function loadSources() {
const picture = document.createElement('picture')
const img = document.createElement('img')

for (const { type, sizes, srcset } of sources.value.slice(0, -1)) {
const source = document.createElement('source')
setAttributes(source, { type, sizes, srcset })
picture.appendChild(source)
}
picture.appendChild(img)

img.onload = (event) => {
// img.decode() avoids jank and flash. A failed decode should not keep the placeholder forever
Promise.resolve(img.decode?.()).catch(() => {}).then(() => {
placeholderLoaded.value = true
emit('load', event)
})
}
img.onerror = (event) => {
emit('error', event)
}

// Attributes are set last, once the `<img>` is a child of the `<picture>`
const { sizes, srcset, src } = sources.value.at(-1)!
setAttributes(img, { sizes, srcset, src, crossorigin: normalizedAttrs.value.crossorigin })
}

onMounted(() => {
if (placeholder.value) {
loadSources()
markFeatureUsage('nuxt-picture')
return
}

const el = Array.isArray(imgEl.value) ? imgEl.value[0] as HTMLImageElement | undefined : imgEl.value
if (!el) {
return
Expand Down
25 changes: 25 additions & 0 deletions src/runtime/utils/props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,31 @@ export interface BaseImageProps<Provider extends keyof ConfiguredImageProviders>
nonce?: string
}

export type PlaceholderProp = boolean | string | number | [w: number, h: number, q?: number, b?: number]

/**
* Resolves the `placeholder` prop into either a ready-to-use URL (when a string
* is provided), the modifiers used to generate a low quality placeholder, or
* `false` when no placeholder should be rendered.
*/
export const resolvePlaceholder = (placeholder: PlaceholderProp | undefined) => {
const value = placeholder === '' ? [10, 10] : placeholder

if (!value) {
return false
}

if (typeof value === 'string') {
return value
}

const [width = 10, height = width, quality = 50, blur = 3] = Array.isArray(value)
? value
: typeof value === 'number' ? [value] : []

return { width, height, quality, blur }
}

export const useImageProps = <Provider extends keyof ConfiguredImageProviders>(props: BaseImageProps<Provider>) => {
const $img = useImage()

Expand Down
Loading
Loading