Unverified Commit 61fab923 authored by Steven's avatar Steven Committed by GitHub

Fix Image `srcset` to ensure the component's `width` is the largest possible image (#18236)

There was a bug when the user defines a width on the Image component, but a larger size image is requested.

This is because the browser uses the `srcset` to decide which image size to request and we had the srcset basically hardcoded.

This PR fixes the behavior so that the `srcset` will never be larger than the `width` defined on the component.

It also fixes a bug where the preload srcset did not match the img srcset.

- Related to #18147 
- Related to #18122
parent 9c65c994
...@@ -42,7 +42,6 @@ const { ...@@ -42,7 +42,6 @@ const {
domains: configDomains, domains: configDomains,
} = imageData } = imageData
configSizes.sort((a, b) => a - b) // smallest to largest configSizes.sort((a, b) => a - b) // smallest to largest
const largestSize = configSizes[configSizes.length - 1]
let cachedObserver: IntersectionObserver let cachedObserver: IntersectionObserver
const IntersectionObserver = const IntersectionObserver =
...@@ -80,15 +79,32 @@ function getObserver(): IntersectionObserver | undefined { ...@@ -80,15 +79,32 @@ function getObserver(): IntersectionObserver | undefined {
)) ))
} }
function getWidthsFromConfig(width: number | undefined) {
if (typeof width !== 'number') {
return configSizes
}
const widths: number[] = []
for (let size of configSizes) {
widths.push(size)
if (size >= width) {
break
}
}
return widths
}
function computeSrc( function computeSrc(
src: string, src: string,
unoptimized: boolean, unoptimized: boolean,
width: number | undefined,
quality?: string quality?: string
): string { ): string {
if (unoptimized) { if (unoptimized) {
return src return src
} }
return callLoader({ src, width: largestSize, quality }) const widths = getWidthsFromConfig(width)
const largest = widths[widths.length - 1]
return callLoader({ src, width: largest, quality })
} }
type CallLoaderProps = { type CallLoaderProps = {
...@@ -104,29 +120,38 @@ function callLoader(loaderProps: CallLoaderProps) { ...@@ -104,29 +120,38 @@ function callLoader(loaderProps: CallLoaderProps) {
type SrcSetData = { type SrcSetData = {
src: string src: string
widths: number[] unoptimized: boolean
quality?: string width: number | undefined
quality: string | undefined
} }
function generateSrcSet({ src, widths, quality }: SrcSetData): string { function generateSrcSet({
src,
unoptimized,
width,
quality,
}: SrcSetData): string | undefined {
// At each breakpoint, generate an image url using the loader, such as: // At each breakpoint, generate an image url using the loader, such as:
// ' www.example.com/foo.jpg?w=480 480w, ' // ' www.example.com/foo.jpg?w=480 480w, '
return widths if (unoptimized) {
.map((width: number) => `${callLoader({ src, width, quality })} ${width}w`) return undefined
}
return getWidthsFromConfig(width)
.map((w) => `${callLoader({ src, width: w, quality })} ${w}w`)
.join(', ') .join(', ')
} }
type PreloadData = { type PreloadData = {
src: string src: string
widths: number[] unoptimized: boolean
width: number | undefined
sizes?: string sizes?: string
unoptimized?: boolean
quality?: string quality?: string
} }
function generatePreload({ function generatePreload({
src, src,
widths, width,
unoptimized = false, unoptimized = false,
sizes, sizes,
quality, quality,
...@@ -140,15 +165,25 @@ function generatePreload({ ...@@ -140,15 +165,25 @@ function generatePreload({
<link <link
rel="preload" rel="preload"
as="image" as="image"
href={computeSrc(src, unoptimized, quality)} href={computeSrc(src, unoptimized, width, quality)}
// @ts-ignore: imagesrcset and imagesizes not yet in the link element type // @ts-ignore: imagesrcset and imagesizes not yet in the link element type
imagesrcset={generateSrcSet({ src, widths, quality })} imagesrcset={generateSrcSet({ src, unoptimized, width, quality })}
imagesizes={sizes} imagesizes={sizes}
/> />
</Head> </Head>
) )
} }
function getInt(x: unknown): number | undefined {
if (typeof x === 'number') {
return x
}
if (typeof x === 'string') {
return parseInt(x, 10)
}
return undefined
}
export default function Image({ export default function Image({
src, src,
sizes, sizes,
...@@ -165,6 +200,13 @@ export default function Image({ ...@@ -165,6 +200,13 @@ export default function Image({
const thisEl = useRef<HTMLImageElement>(null) const thisEl = useRef<HTMLImageElement>(null)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (!src) {
throw new Error(
`Image is missing required "src" property. Make sure you pass "src" in props to the \`next/image\` component. Received: ${JSON.stringify(
{ width, height, quality, unsized }
)}`
)
}
if (!VALID_LOADING_VALUES.includes(loading)) { if (!VALID_LOADING_VALUES.includes(loading)) {
throw new Error( throw new Error(
`Image with src "${src}" has invalid "loading" property. Provided "${loading}" should be one of ${VALID_LOADING_VALUES.map( `Image with src "${src}" has invalid "loading" property. Provided "${loading}" should be one of ${VALID_LOADING_VALUES.map(
...@@ -200,58 +242,23 @@ export default function Image({ ...@@ -200,58 +242,23 @@ export default function Image({
} }
}, [thisEl, lazy]) }, [thisEl, lazy])
// Generate attribute values let widthInt = getInt(width)
const imgSrc = computeSrc(src, unoptimized, quality) let heightInt = getInt(height)
const imgSrcSet = !unoptimized
? generateSrcSet({
src,
widths: configSizes,
quality,
})
: undefined
let imgAttributes:
| {
src: string
srcSet?: string
}
| {
'data-src': string
'data-srcset'?: string
}
if (!lazy) {
imgAttributes = {
src: imgSrc,
}
if (imgSrcSet) {
imgAttributes.srcSet = imgSrcSet
}
} else {
imgAttributes = {
'data-src': imgSrc,
}
if (imgSrcSet) {
imgAttributes['data-srcset'] = imgSrcSet
}
className = className ? className + ' __lazy' : '__lazy'
}
let divStyle: React.CSSProperties | undefined let divStyle: React.CSSProperties | undefined
let imgStyle: React.CSSProperties | undefined let imgStyle: React.CSSProperties | undefined
let wrapperStyle: React.CSSProperties | undefined let wrapperStyle: React.CSSProperties | undefined
if ( if (
typeof height !== 'undefined' && typeof widthInt !== 'undefined' &&
typeof width !== 'undefined' && typeof heightInt !== 'undefined' &&
!unsized !unsized
) { ) {
// <Image src="i.png" width={100} height={100} /> // <Image src="i.png" width={100} height={100} />
// <Image src="i.png" width="100" height="100" /> // <Image src="i.png" width="100" height="100" />
const quotient = const quotient = heightInt / widthInt
parseInt(height as string, 10) / parseInt(width as string, 10)
const ratio = isNaN(quotient) ? 1 : quotient * 100 const ratio = isNaN(quotient) ? 1 : quotient * 100
wrapperStyle = { wrapperStyle = {
maxWidth: '100%', maxWidth: '100%',
width, width: widthInt,
} }
divStyle = { divStyle = {
position: 'relative', position: 'relative',
...@@ -266,8 +273,8 @@ export default function Image({ ...@@ -266,8 +273,8 @@ export default function Image({
width: '100%', width: '100%',
} }
} else if ( } else if (
typeof height === 'undefined' && typeof widthInt === 'undefined' &&
typeof width === 'undefined' && typeof heightInt === 'undefined' &&
unsized unsized
) { ) {
// <Image src="i.png" unsized /> // <Image src="i.png" unsized />
...@@ -288,6 +295,41 @@ export default function Image({ ...@@ -288,6 +295,41 @@ export default function Image({
} }
} }
// Generate attribute values
const imgSrc = computeSrc(src, unoptimized, widthInt, quality)
const imgSrcSet = generateSrcSet({
src,
width: widthInt,
unoptimized,
quality,
})
let imgAttributes:
| {
src: string
srcSet?: string
}
| {
'data-src': string
'data-srcset'?: string
}
if (!lazy) {
imgAttributes = {
src: imgSrc,
}
if (imgSrcSet) {
imgAttributes.srcSet = imgSrcSet
}
} else {
imgAttributes = {
'data-src': imgSrc,
}
if (imgSrcSet) {
imgAttributes['data-srcset'] = imgSrcSet
}
className = className ? className + ' __lazy' : '__lazy'
}
// No need to add preloads on the client side--by the time the application is hydrated, // No need to add preloads on the client side--by the time the application is hydrated,
// it's too late for preloads // it's too late for preloads
const shouldPreload = priority && typeof window === 'undefined' const shouldPreload = priority && typeof window === 'undefined'
...@@ -298,7 +340,7 @@ export default function Image({ ...@@ -298,7 +340,7 @@ export default function Image({
{shouldPreload {shouldPreload
? generatePreload({ ? generatePreload({
src, src,
widths: configSizes, width: widthInt,
unoptimized, unoptimized,
sizes, sizes,
quality, quality,
......
module.exports = { module.exports = {
images: { images: {
sizes: [480, 1024, 1600], sizes: [480, 1024, 1600, 2000],
path: 'https://example.com/myaccount/', path: 'https://example.com/myaccount/',
loader: 'imgix', loader: 'imgix',
}, },
......
...@@ -19,7 +19,7 @@ const Page = () => { ...@@ -19,7 +19,7 @@ const Page = () => {
data-demo="demo-value" data-demo="demo-value"
src="bar.jpg" src="bar.jpg"
loading="eager" loading="eager"
width={300} width={1024}
height={400} height={400}
/> />
<Image <Image
...@@ -39,7 +39,6 @@ const Page = () => { ...@@ -39,7 +39,6 @@ const Page = () => {
width={300} width={300}
height={400} height={400}
/> />
<Image id="priority-image" priority src="withpriority.png" />
<Image <Image
id="priority-image" id="priority-image"
priority priority
......
...@@ -9,7 +9,7 @@ const Lazy = () => { ...@@ -9,7 +9,7 @@ const Lazy = () => {
id="lazy-top" id="lazy-top"
src="foo1.jpg" src="foo1.jpg"
height={400} height={400}
width={300} width={1024}
loading="lazy" loading="lazy"
></Image> ></Image>
<div style={{ height: '2000px' }}></div> <div style={{ height: '2000px' }}></div>
...@@ -35,7 +35,7 @@ const Lazy = () => { ...@@ -35,7 +35,7 @@ const Lazy = () => {
id="lazy-without-attribute" id="lazy-without-attribute"
src="foo4.jpg" src="foo4.jpg"
height={400} height={400}
width={300} width={800}
></Image> ></Image>
<div style={{ height: '2000px' }}></div> <div style={{ height: '2000px' }}></div>
<Image <Image
...@@ -43,7 +43,7 @@ const Lazy = () => { ...@@ -43,7 +43,7 @@ const Lazy = () => {
src="foo5.jpg" src="foo5.jpg"
loading="eager" loading="eager"
height={400} height={400}
width={300} width={1900}
></Image> ></Image>
</div> </div>
) )
......
...@@ -33,27 +33,23 @@ function runTests() { ...@@ -33,27 +33,23 @@ function runTests() {
}) })
it('should modify src with the loader', async () => { it('should modify src with the loader', async () => {
expect(await browser.elementById('basic-image').getAttribute('src')).toBe( expect(await browser.elementById('basic-image').getAttribute('src')).toBe(
'https://example.com/myaccount/foo.jpg?auto=format&w=1600&q=60' 'https://example.com/myaccount/foo.jpg?auto=format&w=480&q=60'
) )
}) })
it('should correctly generate src even if preceding slash is included in prop', async () => { it('should correctly generate src even if preceding slash is included in prop', async () => {
expect( expect(
await browser.elementById('preceding-slash-image').getAttribute('src') await browser.elementById('preceding-slash-image').getAttribute('src')
).toBe('https://example.com/myaccount/fooslash.jpg?auto=format&w=1600') ).toBe('https://example.com/myaccount/fooslash.jpg?auto=format&w=480')
}) })
it('should add a srcset based on the loader', async () => { it('should add a srcset based on the loader', async () => {
expect( expect(
await browser.elementById('basic-image').getAttribute('srcset') await browser.elementById('basic-image').getAttribute('srcset')
).toBe( ).toBe('https://example.com/myaccount/foo.jpg?auto=format&w=480&q=60 480w')
'https://example.com/myaccount/foo.jpg?auto=format&w=480&q=60 480w, https://example.com/myaccount/foo.jpg?auto=format&w=1024&q=60 1024w, https://example.com/myaccount/foo.jpg?auto=format&w=1600&q=60 1600w'
)
}) })
it('should add a srcset even with preceding slash in prop', async () => { it('should add a srcset even with preceding slash in prop', async () => {
expect( expect(
await browser.elementById('preceding-slash-image').getAttribute('srcset') await browser.elementById('preceding-slash-image').getAttribute('srcset')
).toBe( ).toBe('https://example.com/myaccount/fooslash.jpg?auto=format&w=480 480w')
'https://example.com/myaccount/fooslash.jpg?auto=format&w=480 480w, https://example.com/myaccount/fooslash.jpg?auto=format&w=1024 1024w, https://example.com/myaccount/fooslash.jpg?auto=format&w=1600 1600w'
)
}) })
it('should support the unoptimized attribute', async () => { it('should support the unoptimized attribute', async () => {
expect( expect(
...@@ -70,10 +66,10 @@ function runTests() { ...@@ -70,10 +66,10 @@ function runTests() {
function lazyLoadingTests() { function lazyLoadingTests() {
it('should have loaded the first image immediately', async () => { it('should have loaded the first image immediately', async () => {
expect(await browser.elementById('lazy-top').getAttribute('src')).toBe( expect(await browser.elementById('lazy-top').getAttribute('src')).toBe(
'https://example.com/myaccount/foo1.jpg?auto=format&w=1600' 'https://example.com/myaccount/foo1.jpg?auto=format&w=1024'
) )
expect(await browser.elementById('lazy-top').getAttribute('srcset')).toBe( expect(await browser.elementById('lazy-top').getAttribute('srcset')).toBe(
'https://example.com/myaccount/foo1.jpg?auto=format&w=480 480w, https://example.com/myaccount/foo1.jpg?auto=format&w=1024 1024w, https://example.com/myaccount/foo1.jpg?auto=format&w=1600 1600w' 'https://example.com/myaccount/foo1.jpg?auto=format&w=480 480w, https://example.com/myaccount/foo1.jpg?auto=format&w=1024 1024w'
) )
}) })
it('should not have loaded the second image immediately', async () => { it('should not have loaded the second image immediately', async () => {
...@@ -101,11 +97,11 @@ function lazyLoadingTests() { ...@@ -101,11 +97,11 @@ function lazyLoadingTests() {
await check(() => { await check(() => {
return browser.elementById('lazy-mid').getAttribute('src') return browser.elementById('lazy-mid').getAttribute('src')
}, 'https://example.com/myaccount/foo2.jpg?auto=format&w=1600') }, 'https://example.com/myaccount/foo2.jpg?auto=format&w=480')
await check(() => { await check(() => {
return browser.elementById('lazy-mid').getAttribute('srcset') return browser.elementById('lazy-mid').getAttribute('srcset')
}, 'https://example.com/myaccount/foo2.jpg?auto=format&w=480 480w, https://example.com/myaccount/foo2.jpg?auto=format&w=1024 1024w, https://example.com/myaccount/foo2.jpg?auto=format&w=1600 1600w') }, 'https://example.com/myaccount/foo2.jpg?auto=format&w=480 480w')
}) })
it('should not have loaded the third image after scrolling down', async () => { it('should not have loaded the third image after scrolling down', async () => {
expect( expect(
...@@ -150,15 +146,17 @@ function lazyLoadingTests() { ...@@ -150,15 +146,17 @@ function lazyLoadingTests() {
await waitFor(200) await waitFor(200)
expect( expect(
await browser.elementById('lazy-without-attribute').getAttribute('src') await browser.elementById('lazy-without-attribute').getAttribute('src')
).toBe('https://example.com/myaccount/foo4.jpg?auto=format&w=1600') ).toBe('https://example.com/myaccount/foo4.jpg?auto=format&w=1024')
expect( expect(
await browser.elementById('lazy-without-attribute').getAttribute('srcset') await browser.elementById('lazy-without-attribute').getAttribute('srcset')
).toBeTruthy() ).toBe(
'https://example.com/myaccount/foo4.jpg?auto=format&w=480 480w, https://example.com/myaccount/foo4.jpg?auto=format&w=1024 1024w'
)
}) })
it('should load the fifth image eagerly, without scrolling', async () => { it('should load the fifth image eagerly, without scrolling', async () => {
expect(await browser.elementById('eager-loading').getAttribute('src')).toBe( expect(await browser.elementById('eager-loading').getAttribute('src')).toBe(
'https://example.com/myaccount/foo5.jpg?auto=format&w=1600' 'https://example.com/myaccount/foo5.jpg?auto=format&w=2000'
) )
expect( expect(
await browser.elementById('eager-loading').getAttribute('srcset') await browser.elementById('eager-loading').getAttribute('srcset')
...@@ -198,14 +196,14 @@ describe('Image Component Tests', () => { ...@@ -198,14 +196,14 @@ describe('Image Component Tests', () => {
it('should add a preload tag for a priority image', async () => { it('should add a preload tag for a priority image', async () => {
expect( expect(
await hasPreloadLinkMatchingUrl( await hasPreloadLinkMatchingUrl(
'https://example.com/myaccount/withpriority.png?auto=format&w=1600' 'https://example.com/myaccount/withpriority.png?auto=format&w=480&q=60'
) )
).toBe(true) ).toBe(true)
}) })
it('should add a preload tag for a priority image with preceding slash', async () => { it('should add a preload tag for a priority image with preceding slash', async () => {
expect( expect(
await hasPreloadLinkMatchingUrl( await hasPreloadLinkMatchingUrl(
'https://example.com/myaccount/fooslash.jpg?auto=format&w=1600' 'https://example.com/myaccount/fooslash.jpg?auto=format&w=480'
) )
).toBe(true) ).toBe(true)
}) })
...@@ -219,7 +217,7 @@ describe('Image Component Tests', () => { ...@@ -219,7 +217,7 @@ describe('Image Component Tests', () => {
it('should add a preload tag for a priority image, with quality', async () => { it('should add a preload tag for a priority image, with quality', async () => {
expect( expect(
await hasPreloadLinkMatchingUrl( await hasPreloadLinkMatchingUrl(
'https://example.com/myaccount/withpriority.png?auto=format&w=1600&q=60' 'https://example.com/myaccount/withpriority.png?auto=format&w=480&q=60'
) )
).toBe(true) ).toBe(true)
}) })
......
...@@ -88,7 +88,7 @@ function runTests(mode) { ...@@ -88,7 +88,7 @@ function runTests(mode) {
await hasRedbox(browser) await hasRedbox(browser)
expect(await getRedboxHeader(browser)).toContain( expect(await getRedboxHeader(browser)).toContain(
'Next Image Optimization requires src to be provided. Make sure you pass them as props to the `next/image` component. Received: {"width":1200}' 'Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {"width":200}'
) )
}) })
......
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