Unverified Commit d8b59f3e authored by Steven's avatar Steven Committed by GitHub

Add errors for invalid `placeholder=blur` usage (#25953)

There are strict conditions for using `placeholder=blur` documented in #25949 but this will give the user a better understanding during `next dev` and links to the error.

- Error when `placeholder=blur` and no `blurDataURL`
- The Error for small images with `placeholder=blur` has been changed to a warning
- Added support for blurring a webp image
- Added error page linking to relevant docs
parent 2cff8090
# `placeholder=blur` without `blurDataURL`
#### Why This Error Occurred
You are attempting use the `next/image` component with `placeholder=blur` property but no `blurDataURL` property.
The `blurDataURL` might be missing because your using a string for `src` instead of a static import.
Or `blurDataURL` might be missing because the static import is an unsupported image format. Only jpg, png, and webp are supported at this time.
#### Possible Ways to Fix It
- Add a [`blurDataURL`](https://nextjs.org/docs/api-reference/next/image#blurdataurl) property, the contents should be a small Data URL to represent the image
- Change the [`src`](https://nextjs.org/docs/api-reference/next/image#src) property to a static import with one of the supported file types: jpg, png, or webp
- Remove the [`placeholder`](https://nextjs.org/docs/api-reference/next/image#placeholder) property, effectively no blur effect
...@@ -2,7 +2,9 @@ import loaderUtils from 'next/dist/compiled/loader-utils' ...@@ -2,7 +2,9 @@ import loaderUtils from 'next/dist/compiled/loader-utils'
import sizeOf from 'image-size' import sizeOf from 'image-size'
import { processBuffer } from '../../../next-server/server/lib/squoosh/main' import { processBuffer } from '../../../next-server/server/lib/squoosh/main'
const PLACEHOLDER_SIZE = 8 const BLUR_IMG_SIZE = 8
const BLUR_QUALITY = 70
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp']
async function nextImageLoader(content) { async function nextImageLoader(content) {
const context = this.rootContext const context = this.rootContext
...@@ -19,20 +21,20 @@ async function nextImageLoader(content) { ...@@ -19,20 +21,20 @@ async function nextImageLoader(content) {
} }
const imageSize = sizeOf(content) const imageSize = sizeOf(content)
let placeholder let blurDataURL
if (extension === 'jpeg' || extension === 'png') { if (VALID_BLUR_EXT.includes(extension)) {
// Shrink the image's largest dimension to 6 pixels // Shrink the image's largest dimension
const resizeOperationOpts = const resizeOperationOpts =
imageSize.width >= imageSize.height imageSize.width >= imageSize.height
? { type: 'resize', width: PLACEHOLDER_SIZE } ? { type: 'resize', width: BLUR_IMG_SIZE }
: { type: 'resize', height: PLACEHOLDER_SIZE } : { type: 'resize', height: BLUR_IMG_SIZE }
const resizedImage = await processBuffer( const resizedImage = await processBuffer(
content, content,
[resizeOperationOpts], [resizeOperationOpts],
extension, extension,
70 BLUR_QUALITY
) )
placeholder = `data:image/${extension};base64,${resizedImage.toString( blurDataURL = `data:image/${extension};base64,${resizedImage.toString(
'base64' 'base64'
)}` )}`
} }
...@@ -41,7 +43,7 @@ async function nextImageLoader(content) { ...@@ -41,7 +43,7 @@ async function nextImageLoader(content) {
src: '/_next' + interpolatedName, src: '/_next' + interpolatedName,
height: imageSize.height, height: imageSize.height,
width: imageSize.width, width: imageSize.width,
placeholder, blurDataURL,
}) })
this.emitFile(interpolatedName, content, null) this.emitFile(interpolatedName, content, null)
......
...@@ -53,7 +53,7 @@ interface StaticImageData { ...@@ -53,7 +53,7 @@ interface StaticImageData {
src: string src: string
height: number height: number
width: number width: number
placeholder?: string blurDataURL?: string
} }
interface StaticRequire { interface StaticRequire {
...@@ -329,9 +329,7 @@ export default function Image({ ...@@ -329,9 +329,7 @@ export default function Image({
)}` )}`
) )
} }
if (staticImageData.placeholder) { blurDataURL = blurDataURL || staticImageData.blurDataURL
blurDataURL = staticImageData.placeholder
}
staticSrc = staticImageData.src staticSrc = staticImageData.src
if (!layout || layout !== 'fill') { if (!layout || layout !== 'fill') {
height = height || staticImageData.height height = height || staticImageData.height
...@@ -347,6 +345,10 @@ export default function Image({ ...@@ -347,6 +345,10 @@ export default function Image({
} }
src = typeof src === 'string' ? src : staticSrc src = typeof src === 'string' ? src : staticSrc
const widthInt = getInt(width)
const heightInt = getInt(height)
const qualityInt = getInt(quality)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (!src) { if (!src) {
throw new Error( throw new Error(
...@@ -374,6 +376,27 @@ export default function Image({ ...@@ -374,6 +376,27 @@ export default function Image({
`Image with src "${src}" has both "priority" and "loading='lazy'" properties. Only one should be used.` `Image with src "${src}" has both "priority" and "loading='lazy'" properties. Only one should be used.`
) )
} }
if (placeholder === 'blur') {
if ((widthInt || 0) * (heightInt || 0) < 1600) {
console.warn(
`Image with src "${src}" is smaller than 40x40. Consider removing the "placeholder='blur'" property to improve performance.`
)
}
if (!blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match next-image-loader
throw new Error(
`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property.
Possible solutions:
- Add a "blurDataURL" property, the contents should be a small Data URL to represent the image
- Change the "src" property to a static import with one of the supported file types: ${VALID_BLUR_EXT.join(
','
)}
- Remove the "placeholder" property, effectively no blur effect
Read more: https://nextjs.org/docs/messages/placeholder-blur-data-url`
)
}
}
} }
let isLazy = let isLazy =
!priority && (loading === 'lazy' || typeof loading === 'undefined') !priority && (loading === 'lazy' || typeof loading === 'undefined')
...@@ -389,14 +412,6 @@ export default function Image({ ...@@ -389,14 +412,6 @@ export default function Image({
}) })
const isVisible = !isLazy || isIntersected const isVisible = !isLazy || isIntersected
const widthInt = getInt(width)
const heightInt = getInt(height)
const qualityInt = getInt(quality)
// Show blur if larger than 5000px such as 100 x 50
const showBlurPlaceholder =
placeholder === 'blur' && (widthInt || 0) * (heightInt || 0) > 5000
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
...@@ -423,7 +438,7 @@ export default function Image({ ...@@ -423,7 +438,7 @@ export default function Image({
objectFit, objectFit,
objectPosition, objectPosition,
...(showBlurPlaceholder ...(placeholder === 'blur'
? { ? {
filter: 'blur(20px)', filter: 'blur(20px)',
backgroundSize: 'cover', backgroundSize: 'cover',
......
...@@ -8,7 +8,7 @@ export default function Page() { ...@@ -8,7 +8,7 @@ export default function Page() {
<Image <Image
priority priority
id="blurry-placeholder" id="blurry-placeholder"
src="/test.jpg" src="/test.ico"
width="400" width="400"
height="400" height="400"
placeholder="blur" placeholder="blur"
...@@ -19,7 +19,7 @@ export default function Page() { ...@@ -19,7 +19,7 @@ export default function Page() {
<Image <Image
id="blurry-placeholder-with-lazy" id="blurry-placeholder-with-lazy"
src="/test.jpg" src="/test.bmp"
width="400" width="400"
height="400" height="400"
placeholder="blur" placeholder="blur"
......
import React from 'react'
import Image from 'next/image'
import testBMP from '../public/test.bmp'
const Page = () => {
return (
<div>
<Image
id="invalid-placeholder-blur-static"
src={testBMP}
placeholder="blur"
/>
</div>
)
}
export default Page
import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<Image id="invalid-placeholder-blur" src="/test.png" placeholder="blur" />
</div>
)
}
export default Page
import React from 'react'
import Image from 'next/image'
import Small from '../public/small.jpg'
const Page = () => {
return (
<div>
<Image id="small-img-import" src={Small} placeholder="blur" />
</div>
)
}
export default Page
...@@ -4,23 +4,13 @@ import Image from 'next/image' ...@@ -4,23 +4,13 @@ import Image from 'next/image'
import testJPG from '../public/test.jpg' import testJPG from '../public/test.jpg'
import testPNG from '../public/test.png' import testPNG from '../public/test.png'
import testWEBP from '../public/test.webp'
import testSVG from '../public/test.svg' import testSVG from '../public/test.svg'
import testGIF from '../public/test.gif' import testGIF from '../public/test.gif'
import testBMP from '../public/test.bmp' import testBMP from '../public/test.bmp'
import testICO from '../public/test.ico' import testICO from '../public/test.ico'
import testWEBP from '../public/test.webp'
import TallImage from '../components/TallImage' import TallImage from '../components/TallImage'
const testFiles = [
testJPG,
testPNG,
testSVG,
testGIF,
testBMP,
testICO,
testWEBP,
]
const Page = () => { const Page = () => {
return ( return (
<div> <div>
...@@ -46,9 +36,14 @@ const Page = () => { ...@@ -46,9 +36,14 @@ const Page = () => {
width="400" width="400"
height="300" height="300"
/> />
{testFiles.map((f, i) => ( <br />
<Image id={`format-test-${i}`} key={i} src={f} placeholder="blur" /> <Image id="blur-png" src={testPNG} placeholder="blur" />
))} <Image id="blur-jpg" src={testJPG} placeholder="blur" />
<Image id="blur-webp" src={testWEBP} placeholder="blur" />
<Image id="static-svg" src={testSVG} />
<Image id="static-gif" src={testGIF} />
<Image id="static-bmp" src={testBMP} />
<Image id="static-ico" src={testICO} />
</div> </div>
) )
} }
......
...@@ -484,6 +484,39 @@ function runTests(mode) { ...@@ -484,6 +484,39 @@ function runTests(mode) {
'Failed to parse src "//assets.example.com/img.jpg" on `next/image`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)' 'Failed to parse src "//assets.example.com/img.jpg" on `next/image`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)'
) )
}) })
it('should show error when string src and placeholder=blur and blurDataURL is missing', async () => {
const browser = await webdriver(appPort, '/invalid-placeholder-blur')
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toContain(
`Image with src "/test.png" has "placeholder='blur'" property but is missing the "blurDataURL" property.`
)
})
it('should show error when static import and placeholder=blur and blurDataUrl is missing', async () => {
const browser = await webdriver(
appPort,
'/invalid-placeholder-blur-static'
)
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatch(
/Image with src "(.*)bmp" has "placeholder='blur'" property but is missing the "blurDataURL" property/
)
})
it('should warn when using a very small image with placeholder=blur', async () => {
const browser = await webdriver(appPort, '/small-img-import')
const warnings = (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
expect(await hasRedbox(browser)).toBe(false)
expect(warnings).toMatch(
/Image with src (.*)jpg(.*) is smaller than 40x40. Consider removing(.*)/gm
)
})
} }
it('should correctly ignore prose styles', async () => { it('should correctly ignore prose styles', async () => {
......
...@@ -22,13 +22,12 @@ const indexPage = new File(join(appDir, 'pages/static.js')) ...@@ -22,13 +22,12 @@ const indexPage = new File(join(appDir, 'pages/static.js'))
const runTests = () => { const runTests = () => {
it('Should allow an image with a static src to omit height and width', async () => { it('Should allow an image with a static src to omit height and width', async () => {
expect(await browser.elementById('basic-static')).toBeTruthy() expect(await browser.elementById('basic-static')).toBeTruthy()
expect(await browser.elementById('format-test-0')).toBeTruthy() expect(await browser.elementById('blur-png')).toBeTruthy()
expect(await browser.elementById('format-test-1')).toBeTruthy() expect(await browser.elementById('blur-jpg')).toBeTruthy()
expect(await browser.elementById('format-test-2')).toBeTruthy() expect(await browser.elementById('static-svg')).toBeTruthy()
expect(await browser.elementById('format-test-3')).toBeTruthy() expect(await browser.elementById('static-gif')).toBeTruthy()
expect(await browser.elementById('format-test-4')).toBeTruthy() expect(await browser.elementById('static-bmp')).toBeTruthy()
expect(await browser.elementById('format-test-5')).toBeTruthy() expect(await browser.elementById('static-ico')).toBeTruthy()
expect(await browser.elementById('format-test-6')).toBeTruthy()
}) })
it('Should automatically provide an image height and width', async () => { it('Should automatically provide an image height and width', async () => {
expect(html).toContain('width:400px;height:300px') expect(html).toContain('width:400px;height:300px')
......
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