diff --git a/docs/2.usage/2.nuxt-picture.md b/docs/2.usage/2.nuxt-picture.md index 78258a5b8..72f4260a4 100644 --- a/docs/2.usage/2.nuxt-picture.md +++ b/docs/2.usage/2.nuxt-picture.md @@ -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 ``](/modules/image/usage/nuxt-img#placeholder). + +```vue + + + + + + + + +``` + +While the placeholder is displayed, `` renders a plain `` without any ``. The real image is loaded in the background using the same `` candidates, and once it is ready the `` 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 `` element while the placeholder is being rendered. + +```vue + +``` + ### `imgAttrs` Allows you to set additional HTML-attributes on the `img` element. diff --git a/src/runtime/components/NuxtImg.vue b/src/runtime/components/NuxtImg.vue index d498adbe2..9d18a08e6 100644 --- a/src/runtime/components/NuxtImg.vue +++ b/src/runtime/components/NuxtImg.vue @@ -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 extends BaseImageProps { custom?: boolean - placeholder?: boolean | string | number | [w: number, h: number, q?: number, b?: number] + placeholder?: PlaceholderProp placeholderClass?: string } @@ -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) }) diff --git a/src/runtime/components/NuxtPicture.vue b/src/runtime/components/NuxtPicture.vue index eb82f407c..fed4e03fc 100644 --- a/src/runtime/components/NuxtPicture.vue +++ b/src/runtime/components/NuxtPicture.vue @@ -2,20 +2,21 @@ @@ -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' @@ -40,6 +41,8 @@ import { useHead, useNuxtApp, useRequestEvent } from '#imports' export interface PictureProps extends BaseImageProps { legacyFormat?: string imgAttrs?: ImgHTMLAttributes & DataAttributes + placeholder?: PlaceholderProp + placeholderClass?: string } defineOptions({ inheritAttrs: false }) @@ -119,6 +122,29 @@ const sources = computed(() => { }) }) +const placeholderLoaded = ref(false) + +// The placeholder is rendered as a plain `` (without any ``) 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] @@ -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) { + for (const key in attrs) { + if (attrs[key]) { + el.setAttribute(key, attrs[key]) + } + } +} + +// Loads the real image off-screen, using the same `` 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 `` is a child of the `` + 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 diff --git a/src/runtime/utils/props.ts b/src/runtime/utils/props.ts index dee657590..f41e15585 100644 --- a/src/runtime/utils/props.ts +++ b/src/runtime/utils/props.ts @@ -33,6 +33,31 @@ export interface BaseImageProps 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 = (props: BaseImageProps) => { const $img = useImage() diff --git a/test/nuxt/picture.test.ts b/test/nuxt/picture.test.ts index c555b587f..9a2c4d8a5 100644 --- a/test/nuxt/picture.test.ts +++ b/test/nuxt/picture.test.ts @@ -1,11 +1,12 @@ import type { VueWrapper } from '@vue/test-utils' import { mount } from '@vue/test-utils' -import { beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { NuxtPicture } from '#components' import { createError, useNuxtApp, useRuntimeConfig, nextTick } from '#imports' import { imageOptions } from '#build/image-options.mjs' import { createImage } from '@nuxt/image/runtime' import type { RuntimeConfig } from 'nuxt/schema' +import type { PlaceholderProp } from '../../src/runtime/utils/props' describe('Renders simple image', () => { let wrapper: VueWrapper @@ -178,6 +179,148 @@ describe('Renders simple image', () => { }) }) +describe('Renders placeholder image', () => { + const src = '/image.png' + + // Captures the off-screen elements used to load the real image + const captureOffscreenImage = () => { + const created: Record = {} + const createElement = document.createElement.bind(document) + vi.spyOn(document, 'createElement').mockImplementation(((tag: string, options?: ElementCreationOptions) => { + const el = createElement(tag, options) + ;(created[tag] ||= []).push(el) + return el + }) as typeof document.createElement) + // pictures rendered by the component contain an `` + const offscreenPictures = () => (created.picture || []).filter(picture => !picture.querySelector('[data-nuxt-pic]')) + return { + offscreenPictures, + offscreenImage: () => offscreenPictures()[0]!.querySelector('img') as HTMLImageElement, + } + } + + // The swap happens after the (async) decode of the loaded image + const finishLoad = async (img: HTMLImageElement) => { + img.onload!(new Event('load')) + await new Promise(resolve => setTimeout(resolve)) + await nextTick() + } + + afterEach(() => { + vi.restoreAllMocks() + }) + + it('renders only a placeholder until the image is loaded', async () => { + const created = captureOffscreenImage() + const wrapper = mount(NuxtPicture, { + propsData: { width: 200, height: 200, src, placeholder: true }, + }) + + expect(wrapper.find('source').exists()).toBe(false) + const img = wrapper.find('img').element + expect(img.getAttribute('src')).toMatchInlineSnapshot(`"/_ipx/f_png&q_50&blur_3&s_10x10/image.png"`) + expect(img.hasAttribute('srcset')).toBe(false) + expect(img.hasAttribute('sizes')).toBe(false) + + // the real image is loaded off-screen with the same candidates + const offscreen = created.offscreenImage() + const offscreenSources = [...offscreen.parentElement!.querySelectorAll('source')] + expect(offscreenSources).toHaveLength(1) + expect(offscreenSources[0]!.type).toBe('image/webp') + expect(offscreenSources[0]!.getAttribute('srcset')).toContain('/_ipx/f_webp&s_640x640/image.png 640w') + expect(offscreen.parentElement?.tagName).toBe('PICTURE') + expect(offscreen.getAttribute('src')).toBe('/_ipx/f_png&s_3072x3072/image.png') + + await finishLoad(offscreen) + + expect(wrapper.findAll('source')).toHaveLength(1) + expect(wrapper.find('img').element.getAttribute('src')).toBe('/_ipx/f_png&s_3072x3072/image.png') + expect(wrapper.find('img').element.getAttribute('srcset')).toContain('/_ipx/f_png&s_640x640/image.png 640w') + expect(wrapper.emitted().load).toHaveLength(1) + }) + + it('keeps the same element when swapping to the real image', async () => { + const created = captureOffscreenImage() + const wrapper = mount(NuxtPicture, { + propsData: { src, placeholder: true }, + }) + const before = wrapper.find('img').element + await finishLoad(created.offscreenImage()) + expect(wrapper.find('img').element).toBe(before) + }) + + it('supports the same placeholder values as ', () => { + const render = (placeholder: PlaceholderProp) => mount(NuxtPicture, { + propsData: { src, placeholder }, + }).find('img').element.getAttribute('src') + + expect(render([50, 25])).toBe('/_ipx/f_png&q_50&blur_3&s_50x25/image.png') + expect(render([50, 25, 75, 5])).toBe('/_ipx/f_png&q_75&blur_5&s_50x25/image.png') + expect(render(15)).toBe('/_ipx/f_png&q_50&blur_3&s_15x15/image.png') + expect(render('/placeholder.png')).toBe('/placeholder.png') + expect(render('')).toBe('/_ipx/f_png&q_50&blur_3&s_10x10/image.png') + }) + + it('uses the legacy format for the generated placeholder', () => { + const wrapper = mount(NuxtPicture, { + propsData: { src, placeholder: true, format: 'avif,webp', legacyFormat: 'jpeg' }, + }) + expect(wrapper.find('img').element.getAttribute('src')).toBe('/_ipx/f_jpeg&q_50&blur_3&s_10x10/image.png') + }) + + it('applies placeholderClass only while the placeholder is shown', async () => { + const created = captureOffscreenImage() + const wrapper = mount(NuxtPicture, { + propsData: { src, placeholder: true, placeholderClass: 'placeholder' }, + attrs: { class: 'picture' }, + }) + expect(wrapper.find('img').classes()).toEqual(['placeholder']) + await finishLoad(created.offscreenImage()) + expect(wrapper.find('img').classes()).toEqual([]) + }) + + it('emits error and keeps the placeholder when the image fails to load', async () => { + const created = captureOffscreenImage() + const wrapper = mount(NuxtPicture, { + propsData: { src, placeholder: true }, + }) + const errorEvent = new Event('error') + ;(created.offscreenImage()).onerror!(errorEvent) + await nextTick() + + expect(wrapper.emitted().error![0]).toStrictEqual([errorEvent]) + expect(wrapper.find('source').exists()).toBe(false) + expect(wrapper.find('img').element.getAttribute('src')).toContain('blur_3') + }) + + it('swaps even if decoding the loaded image fails', async () => { + const created = captureOffscreenImage() + const wrapper = mount(NuxtPicture, { + propsData: { src, placeholder: true }, + }) + const offscreen = created.offscreenImage() + offscreen.decode = () => Promise.reject(new Error('decode failed')) + offscreen.onload!(new Event('load')) + await vi.waitFor(() => expect(wrapper.find('source').exists()).toBe(true)) + }) + + it('does not render a placeholder for svg sources', () => { + const created = captureOffscreenImage() + const wrapper = mount(NuxtPicture, { + propsData: { src: '/image.svg', placeholder: true }, + }) + expect(wrapper.html()).toMatchInlineSnapshot('""') + expect(created.offscreenPictures()).toHaveLength(0) + }) + + it('renders the regular markup without the placeholder prop', () => { + const created = captureOffscreenImage() + const wrapper = mount(NuxtPicture, { propsData: { src } }) + expect(wrapper.find('source').exists()).toBe(true) + expect(created.offscreenPictures()).toHaveLength(0) + }) +}) + describe('Renders image, applies module config', () => { let nuxtApp: ReturnType let config: RuntimeConfig diff --git a/test/unit/bundle.test.ts b/test/unit/bundle.test.ts index 955804eee..7e4e7164e 100644 --- a/test/unit/bundle.test.ts +++ b/test/unit/bundle.test.ts @@ -21,7 +21,7 @@ describe.skipIf(process.env.ECOSYSTEM_CI || isWindows)('nuxt image bundle size', image: { provider: 'ipx' }, }) - expect(roundToKilobytes(withImage.totalBytes - withoutImage.totalBytes)).toMatchInlineSnapshot(`"12.4k"`) + expect(roundToKilobytes(withImage.totalBytes - withoutImage.totalBytes)).toMatchInlineSnapshot(`"13.5k"`) }) })