Unverified Commit c76170e8 authored by Joon Park's avatar Joon Park Committed by GitHub

Add experimental blurry placeholder to image component (#24153)

This is the image component implementation of the blurry placeholder as described in #24004. The matching server side implementation is currently planned.

## Feature

- [x] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [x] Related issue #18858 
- [x] Integration tests added

(Documentation and telemetry to follow after server side is implemented)
parent 9bbb968c
...@@ -1084,6 +1084,7 @@ export default async function getBaseWebpackConfig( ...@@ -1084,6 +1084,7 @@ export default async function getBaseWebpackConfig(
domains: config.images.domains, domains: config.images.domains,
} }
: {}), : {}),
enableBlurryPlaceholder: config.experimental.enableBlurryPlaceholder,
}), }),
'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath), 'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath),
'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites), 'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites),
......
...@@ -45,6 +45,8 @@ const VALID_LAYOUT_VALUES = [ ...@@ -45,6 +45,8 @@ const VALID_LAYOUT_VALUES = [
] as const ] as const
type LayoutValue = typeof VALID_LAYOUT_VALUES[number] type LayoutValue = typeof VALID_LAYOUT_VALUES[number]
type PlaceholderValue = 'blur' | 'empty'
type ImgElementStyle = NonNullable<JSX.IntrinsicElements['img']['style']> type ImgElementStyle = NonNullable<JSX.IntrinsicElements['img']['style']>
export type ImageProps = Omit< export type ImageProps = Omit<
...@@ -72,6 +74,13 @@ export type ImageProps = Omit< ...@@ -72,6 +74,13 @@ export type ImageProps = Omit<
height: number | string height: number | string
layout?: Exclude<LayoutValue, 'fill'> layout?: Exclude<LayoutValue, 'fill'>
} }
) &
(
| {
placeholder?: Exclude<PlaceholderValue, 'blur'>
blurDataURL?: never
}
| { placeholder: 'blur'; blurDataURL: string }
) )
const { const {
...@@ -80,6 +89,7 @@ const { ...@@ -80,6 +89,7 @@ const {
loader: configLoader, loader: configLoader,
path: configPath, path: configPath,
domains: configDomains, domains: configDomains,
enableBlurryPlaceholder: configEnableBlurryPlaceholder,
} = } =
((process.env.__NEXT_IMAGE_OPTS as any) as ImageConfig) || imageConfigDefault ((process.env.__NEXT_IMAGE_OPTS as any) as ImageConfig) || imageConfigDefault
// sort smallest to largest // sort smallest to largest
...@@ -211,6 +221,26 @@ function defaultImageLoader(loaderProps: ImageLoaderProps) { ...@@ -211,6 +221,26 @@ function defaultImageLoader(loaderProps: ImageLoaderProps) {
) )
} }
// See https://stackoverflow.com/q/39777833/266535 for why we use this ref
// handler instead of the img's onLoad attribute.
function removePlaceholder(
element: HTMLImageElement | null,
placeholder: PlaceholderValue
) {
if (placeholder === 'blur' && element) {
if (element.complete) {
// If the real image fails to load, this will still remove the placeholder.
// This is the desired behavior for now, and will be revisited when error
// handling is worked on for the image component itself.
element.style.backgroundImage = 'none'
} else {
element.onload = () => {
element.style.backgroundImage = 'none'
}
}
}
}
export default function Image({ export default function Image({
src, src,
sizes, sizes,
...@@ -224,6 +254,8 @@ export default function Image({ ...@@ -224,6 +254,8 @@ export default function Image({
objectFit, objectFit,
objectPosition, objectPosition,
loader = defaultImageLoader, loader = defaultImageLoader,
placeholder = 'empty',
blurDataURL,
...all ...all
}: ImageProps) { }: ImageProps) {
let rest: Partial<ImageProps> = all let rest: Partial<ImageProps> = all
...@@ -241,6 +273,10 @@ export default function Image({ ...@@ -241,6 +273,10 @@ export default function Image({
delete rest['layout'] delete rest['layout']
} }
if (!configEnableBlurryPlaceholder) {
placeholder = 'empty'
}
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (!src) { if (!src) {
throw new Error( throw new Error(
...@@ -293,6 +329,12 @@ export default function Image({ ...@@ -293,6 +329,12 @@ export default function Image({
const heightInt = getInt(height) const heightInt = getInt(height)
const qualityInt = getInt(quality) const qualityInt = getInt(quality)
const MIN_IMG_SIZE_FOR_PLACEHOLDER = 5000
const tooSmallForBlurryPlaceholder =
widthInt && heightInt && widthInt * heightInt < MIN_IMG_SIZE_FOR_PLACEHOLDER
const shouldShowBlurryPlaceholder =
placeholder === 'blur' && !tooSmallForBlurryPlaceholder
let wrapperStyle: JSX.IntrinsicElements['div']['style'] | undefined let wrapperStyle: JSX.IntrinsicElements['div']['style'] | undefined
let sizerStyle: JSX.IntrinsicElements['div']['style'] | undefined let sizerStyle: JSX.IntrinsicElements['div']['style'] | undefined
let sizerSvg: string | undefined let sizerSvg: string | undefined
...@@ -318,6 +360,13 @@ export default function Image({ ...@@ -318,6 +360,13 @@ export default function Image({
objectFit, objectFit,
objectPosition, objectPosition,
...(shouldShowBlurryPlaceholder
? {
backgroundSize: 'cover',
backgroundImage: `url("${blurDataURL}")`,
}
: undefined),
} }
if ( if (
typeof widthInt !== 'undefined' && typeof widthInt !== 'undefined' &&
...@@ -464,7 +513,10 @@ export default function Image({ ...@@ -464,7 +513,10 @@ export default function Image({
{...imgAttributes} {...imgAttributes}
decoding="async" decoding="async"
className={className} className={className}
ref={setRef} ref={(element) => {
setRef(element)
removePlaceholder(element, placeholder)
}}
style={imgStyle} style={imgStyle}
/> />
{priority ? ( {priority ? (
......
...@@ -61,6 +61,7 @@ export type NextConfig = { [key: string]: any } & { ...@@ -61,6 +61,7 @@ export type NextConfig = { [key: string]: any } & {
turboMode: boolean turboMode: boolean
eslint?: boolean eslint?: boolean
reactRoot: boolean reactRoot: boolean
enableBlurryPlaceholder: boolean
} }
} }
...@@ -117,6 +118,7 @@ export const defaultConfig: NextConfig = { ...@@ -117,6 +118,7 @@ export const defaultConfig: NextConfig = {
turboMode: false, turboMode: false,
eslint: false, eslint: false,
reactRoot: Number(process.env.NEXT_PRIVATE_REACT_ROOT) > 0, reactRoot: Number(process.env.NEXT_PRIVATE_REACT_ROOT) > 0,
enableBlurryPlaceholder: false,
}, },
future: { future: {
strictPostcssConfiguration: false, strictPostcssConfiguration: false,
......
...@@ -13,6 +13,7 @@ export type ImageConfig = { ...@@ -13,6 +13,7 @@ export type ImageConfig = {
loader: LoaderValue loader: LoaderValue
path: string path: string
domains?: string[] domains?: string[]
enableBlurryPlaceholder: boolean
} }
export const imageConfigDefault: ImageConfig = { export const imageConfigDefault: ImageConfig = {
...@@ -21,4 +22,5 @@ export const imageConfigDefault: ImageConfig = { ...@@ -21,4 +22,5 @@ export const imageConfigDefault: ImageConfig = {
path: '/_next/image', path: '/_next/image',
loader: 'default', loader: 'default',
domains: [], domains: [],
enableBlurryPlaceholder: false,
} }
import React from 'react'
import Image from 'next/image'
export default function Page() {
return (
<div>
<p>Blurry Placeholder</p>
<Image
priority
id="blurry-placeholder"
src="/test.jpg"
width="400"
height="400"
placeholder="blur"
blurDataURL="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/8QAMwABAQEAAAAAAAAAAAAAAAAAAAcJEAABAwUAAwAAAAAAAAAAAAAFAAYRAQMEEyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E"
/>
</div>
)
}
...@@ -587,7 +587,10 @@ describe('Image Component Tests', () => { ...@@ -587,7 +587,10 @@ describe('Image Component Tests', () => {
nextConfig, nextConfig,
` `
module.exports = { module.exports = {
target: 'serverless' target: 'serverless',
experimental: {
enableBlurryPlaceholder: true,
},
} }
` `
) )
...@@ -600,6 +603,29 @@ describe('Image Component Tests', () => { ...@@ -600,6 +603,29 @@ describe('Image Component Tests', () => {
await killApp(app) await killApp(app)
}) })
it('should have blurry placeholder when enabled', async () => {
const html = await renderViaHTTP(appPort, '/blurry-placeholder')
expect(html).toContain(
'background-image:url(&quot;data:image/svg+xml,%3Csvg xmlns=&#x27;http://www.w3.org/2000/svg&#x27; width=&#x27;400&#x27; height=&#x27;400&#x27; viewBox=&#x27;0 0 400 400&#x27;%3E%3Cfilter id=&#x27;blur&#x27; filterUnits=&#x27;userSpaceOnUse&#x27; color-interpolation-filters=&#x27;sRGB&#x27;%3E%3CfeGaussianBlur stdDeviation=&#x27;20&#x27; edgeMode=&#x27;duplicate&#x27; /%3E%3CfeComponentTransfer%3E%3CfeFuncA type=&#x27;discrete&#x27; tableValues=&#x27;1 1&#x27; /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter=&#x27;url(%23blur)&#x27; href=&#x27;data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMDAwMDAwQEBAQFBQUFBQcHBgYHBwsICQgJCAsRCwwLCwwLEQ8SDw4PEg8bFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/8QAMwABAQEAAAAAAAAAAAAAAAAAAAcJEAABAwUAAwAAAAAAAAAAAAAFAAYRAQMEEyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==&#x27; x=&#x27;0&#x27; y=&#x27;0&#x27; height=&#x27;100%25&#x27; width=&#x27;100%25&#x27;/%3E%3C/svg%3E&quot;)'
)
})
it('should remove blurry placeholder after image loads', async () => {
let browser
try {
browser = await webdriver(appPort, '/blurry-placeholder')
const id = 'blurry-placeholder'
const backgroundImage = await browser.eval(
`window.getComputedStyle(document.getElementById('${id}')).getPropertyValue('background-image')`
)
expect(backgroundImage).toBe('none')
} finally {
if (browser) {
await browser.close()
}
}
})
runTests('serverless') runTests('serverless')
}) })
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment