Unverified Commit 9569f5a3 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Deprecate Image `unsized` property and add `layout="fill"` (#18562)

This PR deprecates the `unsized` property from NextImage because the property did not accomplish the desired effect.

Users should rely on one of the new layouts instead:

- `<Image layout="fixed" />`
- `<Image layout="intrinsic" />`
- `<Image layout="responsive" />`
- `<Image layout="fill" />`

The `unsized` property will continue to work as-is in production but is deprecated and will throw in dev.

---

### TODO:
- [x] test `layout=fill` in typescript types
- [x] test `layout=fill` render behavior
- [x] test that `unsized` switches to `layout=fill`
- [x] test `next dev` erroring on `unsized`
- [ ] layout docs (tracked in issue #18554)
- [ ] both `layout=fill` and `layout=responsive` use all deviceWidths in the srcset

---

Fixes #18541 
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent 9de734a2
...@@ -46,14 +46,14 @@ export default Home ...@@ -46,14 +46,14 @@ export default Home
`Image` accepts the following props: `Image` accepts the following props:
- `src` - The path or URL to the source image. This is required. - `src` - The path or URL to the source image. This is required.
- `width` - The intrinsic width of the source image in pixels. Must be an integer without a unit. Required unless `unsized` is true. - `width` - The intrinsic width of the source image in pixels. Must be an integer without a unit. Required unless `layout="fill"`.
- `height` - The intrinsic height of the source image, in pixels. Must be an integer without a unit. Required unless `unsized` is true. - `height` - The intrinsic height of the source image, in pixels. Must be an integer without a unit. Required unless `layout="fill"`.
- `layout` - The rendered layout of the image. If `fixed`, the image dimensions will not change as the viewport changes (no responsiveness). If `intrinsic`, the image will scale the dimensions down for smaller viewports but maintain the original dimensions for larger viewports. If `responsive`, the image will scale the dimensions down for smaller viewports and scale up for larger viewports. Default `intrinsic`. - `layout` - The rendered layout of the image. If `fixed`, the image dimensions will not change as the viewport changes (no responsiveness). If `intrinsic`, the image will scale the dimensions down for smaller viewports but maintain the original dimensions for larger viewports. If `responsive`, the image will scale the dimensions down for smaller viewports and scale up for larger viewports. If `fill`, the image will stretch both width and height to the dimensions of the parent element. Default `intrinsic`.
- `sizes` - Defines what proportion of the screen you expect the image to take up. Recommended, as it helps serve the correct sized image to each device. [More info](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-sizes). - `sizes` - Defines what proportion of the screen you expect the image to take up. Recommended, as it helps serve the correct sized image to each device. [More info](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-sizes).
- `quality` - The quality of the optimized image, an integer between 1 and 100 where 100 is the best quality. Default 75. - `quality` - The quality of the optimized image, an integer between 1 and 100 where 100 is the best quality. Default 75.
- `loading` - The loading behavior. When `lazy`, defer loading the image until it reaches a calculated distance from the viewport. When `eager`, load the image immediately. Default `lazy`. [More info](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-loading) - `loading` - The loading behavior. When `lazy`, defer loading the image until it reaches a calculated distance from the viewport. When `eager`, load the image immediately. Default `lazy`. [More info](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-loading)
- `priority` - When true, the image will be considered high priority and [preload](https://web.dev/preload-responsive-images/). - `priority` - When true, the image will be considered high priority and [preload](https://web.dev/preload-responsive-images/).
- `unoptimized` - When true, the source image will be served as-is instead of resizing and changing quality. - `unoptimized` - When true, the source image will be served as-is instead of resizing and changing quality.
- `unsized` - When true, the `width` and `height` requirement can by bypassed. Should _not_ be used with above-the-fold images. Should _not_ be used with `priority`. - `unsized` - **Deprecated** When true, the `width` and `height` requirement can by bypassed. Use the `layout` property instead!
All other properties on the `<Image>` component will be passed to the underlying `<img>` element. All other properties on the `<Image>` component will be passed to the underlying `<img>` element.
...@@ -14,6 +14,7 @@ const loaders = new Map<LoaderKey, (props: LoaderProps) => string>([ ...@@ -14,6 +14,7 @@ const loaders = new Map<LoaderKey, (props: LoaderProps) => string>([
type LoaderKey = 'imgix' | 'cloudinary' | 'akamai' | 'default' type LoaderKey = 'imgix' | 'cloudinary' | 'akamai' | 'default'
const VALID_LAYOUT_VALUES = [ const VALID_LAYOUT_VALUES = [
'fill',
'fixed', 'fixed',
'intrinsic', 'intrinsic',
'responsive', 'responsive',
...@@ -37,11 +38,20 @@ type ImageProps = Omit< ...@@ -37,11 +38,20 @@ type ImageProps = Omit<
quality?: number | string quality?: number | string
priority?: boolean priority?: boolean
loading?: LoadingValue loading?: LoadingValue
layout?: LayoutValue
unoptimized?: boolean unoptimized?: boolean
} & ( } & (
| { width: number | string; height: number | string; unsized?: false } | {
| { width?: number | string; height?: number | string; unsized: true } width?: never
height?: never
/** @deprecated Use `layout="fill"` instead */
unsized: true
}
| { width?: never; height?: never; layout: 'fill' }
| {
width: number | string
height: number | string
layout?: Exclude<LayoutValue, 'fill'>
}
) )
const imageData: ImageData = process.env.__NEXT_IMAGE_OPTS as any const imageData: ImageData = process.env.__NEXT_IMAGE_OPTS as any
...@@ -210,21 +220,34 @@ export default function Image({ ...@@ -210,21 +220,34 @@ export default function Image({
unoptimized = false, unoptimized = false,
priority = false, priority = false,
loading, loading,
layout,
className, className,
quality, quality,
width, width,
height, height,
unsized, ...all
...rest
}: ImageProps) { }: ImageProps) {
const thisEl = useRef<HTMLImageElement>(null) const thisEl = useRef<HTMLImageElement>(null)
let rest: Partial<ImageProps> = all
let layout: NonNullable<LayoutValue> = sizes ? 'responsive' : 'intrinsic'
let unsized = false
if ('unsized' in rest) {
unsized = Boolean(rest.unsized)
// Remove property so it's not spread into image:
delete rest['unsized']
} else if ('layout' in rest) {
// Override default layout if the user specified one:
if (rest.layout) layout = rest.layout
// Remove property so it's not spread into image:
delete rest['layout']
}
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (!src) { if (!src) {
throw new Error( throw new Error(
`Image is missing required "src" property. Make sure you pass "src" in props to the \`next/image\` component. Received: ${JSON.stringify( `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 } { width, height, quality }
)}` )}`
) )
} }
...@@ -244,16 +267,13 @@ export default function Image({ ...@@ -244,16 +267,13 @@ export default function Image({
} }
if (priority && loading === 'lazy') { if (priority && loading === 'lazy') {
throw new Error( throw new Error(
`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 (unsized) {
throw new Error(
if (!layout) { `Image with src "${src}" has deprecated "unsized" property, which was removed in favor of the "layout='fill'" property`
if (sizes) { )
layout = 'responsive'
} else {
layout = 'intrinsic'
} }
} }
...@@ -290,69 +310,101 @@ export default function Image({ ...@@ -290,69 +310,101 @@ export default function Image({
const heightInt = getInt(height) const heightInt = getInt(height)
const qualityInt = getInt(quality) const qualityInt = getInt(quality)
let wrapperStyle: React.CSSProperties | undefined let wrapperStyle: JSX.IntrinsicElements['div']['style'] | undefined
let sizerStyle: React.CSSProperties | undefined let sizerStyle: JSX.IntrinsicElements['div']['style'] | undefined
let sizerSvg: string | undefined let sizerSvg: string | undefined
let imgStyle: React.CSSProperties | undefined let imgStyle: JSX.IntrinsicElements['img']['style'] = {
visibility: lazy ? 'hidden' : 'visible',
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
right: 0,
boxSizing: 'border-box',
padding: 0,
border: 'none',
margin: 'auto',
display: 'block',
width: 0,
height: 0,
minWidth: '100%',
maxWidth: '100%',
minHeight: '100%',
maxHeight: '100%',
}
if ( if (
typeof widthInt !== 'undefined' && typeof widthInt !== 'undefined' &&
typeof heightInt !== 'undefined' && typeof heightInt !== 'undefined' &&
!unsized layout !== 'fill'
) { ) {
// <Image src="i.png" width="100" height="100" /> // <Image src="i.png" width="100" height="100" />
const quotient = heightInt / widthInt const quotient = heightInt / widthInt
const paddingTop = isNaN(quotient) ? '100%' : `${quotient * 100}%` const paddingTop = isNaN(quotient) ? '100%' : `${quotient * 100}%`
if (layout === 'responsive') { if (layout === 'responsive') {
// <Image src="i.png" width="100" height="100" layout="responsive" /> // <Image src="i.png" width="100" height="100" layout="responsive" />
wrapperStyle = { position: 'relative' } wrapperStyle = {
sizerStyle = { paddingTop } display: 'block',
overflow: 'hidden',
position: 'relative',
boxSizing: 'border-box',
margin: 0,
}
sizerStyle = { display: 'block', boxSizing: 'border-box', paddingTop }
} else if (layout === 'intrinsic') { } else if (layout === 'intrinsic') {
// <Image src="i.png" width="100" height="100" layout="intrinsic" /> // <Image src="i.png" width="100" height="100" layout="intrinsic" />
wrapperStyle = { wrapperStyle = {
display: 'inline-block', display: 'inline-block',
position: 'relative',
maxWidth: '100%', maxWidth: '100%',
overflow: 'hidden',
position: 'relative',
boxSizing: 'border-box',
margin: 0,
} }
sizerStyle = { sizerStyle = {
boxSizing: 'border-box',
display: 'block',
maxWidth: '100%', maxWidth: '100%',
} }
sizerSvg = `<svg width="${widthInt}" height="${heightInt}" xmlns="http://www.w3.org/2000/svg" version="1.1"/>` sizerSvg = `<svg width="${widthInt}" height="${heightInt}" xmlns="http://www.w3.org/2000/svg" version="1.1"/>`
} else if (layout === 'fixed') { } else if (layout === 'fixed') {
// <Image src="i.png" width="100" height="100" layout="fixed" /> // <Image src="i.png" width="100" height="100" layout="fixed" />
wrapperStyle = { wrapperStyle = {
overflow: 'hidden',
boxSizing: 'border-box',
display: 'inline-block', display: 'inline-block',
position: 'relative', position: 'relative',
width: widthInt, width: widthInt,
height: heightInt, height: heightInt,
} }
} }
imgStyle = {
visibility: lazy ? 'hidden' : 'visible',
height: '100%',
left: '0',
position: 'absolute',
top: '0',
width: '100%',
}
} else if ( } else if (
typeof widthInt === 'undefined' && typeof widthInt === 'undefined' &&
typeof heightInt === 'undefined' && typeof heightInt === 'undefined' &&
unsized layout === 'fill'
) { ) {
// <Image src="i.png" unsized /> // <Image src="i.png" layout="fill" />
if (process.env.NODE_ENV !== 'production') { wrapperStyle = {
if (priority) { display: 'block',
// <Image src="i.png" unsized priority /> overflow: 'hidden',
console.warn(
`Image with src "${src}" has both "priority" and "unsized" properties. Only one should be used.` position: 'absolute',
) top: 0,
} left: 0,
bottom: 0,
right: 0,
boxSizing: 'border-box',
margin: 0,
} }
} else { } else {
// <Image src="i.png" /> // <Image src="i.png" />
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
throw new Error( throw new Error(
`Image with src "${src}" must use "width" and "height" properties or "unsized" property.` `Image with src "${src}" must use "width" and "height" properties or "layout='fill'" property.`
) )
} }
} }
...@@ -396,6 +448,11 @@ export default function Image({ ...@@ -396,6 +448,11 @@ export default function Image({
// it's too late for preloads // it's too late for preloads
const shouldPreload = priority && typeof window === 'undefined' const shouldPreload = priority && typeof window === 'undefined'
if (unsized) {
wrapperStyle = undefined
sizerStyle = undefined
imgStyle = undefined
}
return ( return (
<div style={wrapperStyle}> <div style={wrapperStyle}>
{shouldPreload {shouldPreload
......
...@@ -4,9 +4,8 @@ import Image from 'next/image' ...@@ -4,9 +4,8 @@ import Image from 'next/image'
const Page = () => { const Page = () => {
return ( return (
<div> <div>
<p>Hello World</p> <p>Home Page</p>
<Image id="basic-image" src="/test.jpg" width="400" height="400"></Image> <Image id="basic-image" src="/test.jpg" width="400" height="400"></Image>
<Image id="unsized-image" src="/test.png" unsized></Image>
<p id="stubtext">This is the index page</p> <p id="stubtext">This is the index page</p>
</div> </div>
) )
......
...@@ -4,8 +4,8 @@ import Image from 'next/image' ...@@ -4,8 +4,8 @@ import Image from 'next/image'
const Page = () => { const Page = () => {
return ( return (
<div> <div>
<p>Hello World</p> <p>Invalid Source</p>
<Image src="https://google.com/test.png" unsized></Image> <Image src="https://google.com/test.png" width="10" height="10" />
</div> </div>
) )
} }
......
import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<p>Invalid Unsized</p>
<Image id="unsized-image" src="/test.png" unsized />
</div>
)
}
export default Page
import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<p>Layout Fill</p>
<div style={{ position: 'relative', width: '600px', height: '350px' }}>
<Image id="fill1" src="/wide.png" layout="fill" />
</div>
<p>Layout Fill</p>
<div style={{ position: 'relative', width: '100vw', height: '100vh' }}>
<Image id="fill2" src="/wide.png" layout="fill" />
</div>
<p>Layout Fill</p>
</div>
)
}
export default Page
...@@ -67,22 +67,6 @@ function runTests(mode) { ...@@ -67,22 +67,6 @@ function runTests(mode) {
return 'result-correct' return 'result-correct'
}, /result-correct/) }, /result-correct/)
await browser.eval(
'document.getElementById("unsized-image").scrollIntoView()'
)
await check(async () => {
const result = await browser.eval(
`document.getElementById('unsized-image').naturalWidth`
)
if (result === 0) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
expect( expect(
await hasImageMatchingUrl( await hasImageMatchingUrl(
browser, browser,
...@@ -204,6 +188,70 @@ function runTests(mode) { ...@@ -204,6 +188,70 @@ function runTests(mode) {
} }
}) })
it('should work with layout-fill to fill the parent but NOT stretch with viewport', async () => {
let browser
try {
browser = await webdriver(appPort, '/layout-fill')
const width = 600
const height = 350
const delta = 150
const id = 'fill1'
await browser.setDimensions({
width: width + delta,
height: height + delta,
})
expect(await getComputed(browser, id, 'width')).toBe(width)
expect(await getComputed(browser, id, 'height')).toBe(height)
await browser.setDimensions({
width: width - delta,
height: height - delta,
})
const newWidth = await getComputed(browser, id, 'width')
const newHeight = await getComputed(browser, id, 'height')
expect(newWidth).toBe(width)
expect(newHeight).toBe(height)
expect(getRatio(newWidth, newHeight)).toBe(getRatio(width, height))
} finally {
if (browser) {
await browser.close()
}
}
})
it('should work with layout-fill to fill the parent and stretch with viewport', async () => {
let browser
try {
browser = await webdriver(appPort, '/layout-fill')
const id = 'fill2'
const width = await getComputed(browser, id, 'width')
const height = await getComputed(browser, id, 'height')
await browser.eval(`document.getElementById("${id}").scrollIntoView()`)
expect(await getComputed(browser, id, 'width')).toBe(width)
expect(await getComputed(browser, id, 'height')).toBe(height)
const delta = 150
const largeWidth = width + delta
const largeHeight = height + delta
await browser.setDimensions({
width: largeWidth,
height: largeHeight,
})
expect(await getComputed(browser, id, 'width')).toBe(largeWidth)
expect(await getComputed(browser, id, 'height')).toBe(largeHeight)
const smallWidth = width - delta
const smallHeight = height - delta
await browser.setDimensions({
width: smallWidth,
height: smallHeight,
})
expect(await getComputed(browser, id, 'width')).toBe(smallWidth)
expect(await getComputed(browser, id, 'height')).toBe(smallHeight)
} finally {
if (browser) {
await browser.close()
}
}
})
if (mode === 'dev') { if (mode === 'dev') {
it('should show missing src error', async () => { it('should show missing src error', async () => {
const browser = await webdriver(appPort, '/missing-src') const browser = await webdriver(appPort, '/missing-src')
...@@ -222,6 +270,15 @@ function runTests(mode) { ...@@ -222,6 +270,15 @@ function runTests(mode) {
'Invalid src prop (https://google.com/test.png) on `next/image`, hostname "google.com" is not configured under images in your `next.config.js`' 'Invalid src prop (https://google.com/test.png) on `next/image`, hostname "google.com" is not configured under images in your `next.config.js`'
) )
}) })
it('should show invalid unsized error', async () => {
const browser = await webdriver(appPort, '/invalid-unsized')
await hasRedbox(browser)
expect(await getRedboxHeader(browser)).toContain(
'Image with src "/test.png" has deprecated "unsized" property, which was removed in favor of the "layout=\'fill\'" property'
)
})
} }
} }
......
...@@ -4,7 +4,7 @@ import Image from 'next/image' ...@@ -4,7 +4,7 @@ import Image from 'next/image'
const Invalid = () => { const Invalid = () => {
return ( return (
<div> <div>
<h1>Hello World</h1> <h1>Invalid TS</h1>
<Image <Image
id="no-width-or-height" id="no-width-or-height"
src="https://via.placeholder.com/500" src="https://via.placeholder.com/500"
......
...@@ -4,36 +4,40 @@ import Image from 'next/image' ...@@ -4,36 +4,40 @@ import Image from 'next/image'
const Page = () => { const Page = () => {
return ( return (
<div> <div>
<p>Hello World</p> <p>Valid TS</p>
<Image <Image
id="width-and-height-num" id="width-and-height-num"
src="https://via.placeholder.com/500" src="https://via.placeholder.com/500"
width={500} width={500}
height={500} height={500}
></Image> />
<Image <Image
id="width-and-height-str" id="width-and-height-str"
src="https://via.placeholder.com/500" src="https://via.placeholder.com/500"
width="500" width="500"
height="500" height="500"
></Image> />
<Image <div style={{ position: 'relative', width: 100, height: 100 }}>
id="unsized-image" <Image
src="https://via.placeholder.com/100" id="layout-fill"
unsized src="https://via.placeholder.com/100"
></Image> layout="fill"
/>
</div>
<Image <Image
id="quality-num" id="quality-num"
src="https://via.placeholder.com/500" src="https://via.placeholder.com/500"
quality={80} quality={80}
unsized width={500}
></Image> height={500}
/>
<Image <Image
id="quality-str" id="quality-str"
src="https://via.placeholder.com/500" src="https://via.placeholder.com/500"
quality="80" quality="80"
unsized width={500}
></Image> height={500}
/>
<p id="stubtext">This is valid usage of the Image component</p> <p id="stubtext">This is valid usage of the Image component</p>
</div> </div>
) )
......
...@@ -45,14 +45,14 @@ describe('TypeScript Image Component', () => { ...@@ -45,14 +45,14 @@ describe('TypeScript Image Component', () => {
const html = await renderViaHTTP(appPort, '/valid', {}) const html = await renderViaHTTP(appPort, '/valid', {})
expect(html).toMatch(/This is valid usage of the Image component/) expect(html).toMatch(/This is valid usage of the Image component/)
expect(output).not.toMatch( expect(output).not.toMatch(
/must use "width" and "height" properties or "unsized" property/ /must use "width" and "height" properties or "layout='fill'" property/
) )
}) })
it('should print error when invalid Image usage', async () => { it('should print error when invalid Image usage', async () => {
await renderViaHTTP(appPort, '/invalid', {}) await renderViaHTTP(appPort, '/invalid', {})
expect(output).toMatch( expect(output).toMatch(
/must use "width" and "height" properties or "unsized" property/ /must use "width" and "height" properties or "layout='fill'" property/
) )
}) })
}) })
......
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