Unverified Commit cbaaaeb0 authored by Alex Castle's avatar Alex Castle Committed by GitHub

Add "fill" mode to `next/future/image` (#38855)

This PR adds a `fill` attribute to the future image component, that behave similarly to the fill mode on the existing image component.

Functionally, it mainly adds `position: "absolute"` and `object-fit: "contain"` to the image element, along with `height: "100%"` and `width: "100%"` to preserve the image aspect ratio. All of these can be overwritten by the user, except for `position: "absolute"`, which will throw an error. This is because changing that property without height and width is likely to cause layout shift.

Because we no longer have the wrapper element, this new version of `fill` requires that the user set `overflow: "hidden"` on the parent element themself, if they want that behavior.

This PR also includes several runtime checks to catch instances where the fill mode may provide unexpected results. These runtime checks warn if:
* The image doesn't have the `sizes` attribute and loads much smaller than the viewport
* The containing element does not have `position: "relative"`
* The image height value is 0
Co-authored-by: 's avatarSteven <229881+styfle@users.noreply.github.com>
parent e9d23d70
...@@ -9,6 +9,7 @@ description: Try the latest Image Optimization with the experimental `next/futur ...@@ -9,6 +9,7 @@ description: Try the latest Image Optimization with the experimental `next/futur
| Version | Changes | | Version | Changes |
| --------- | -------------------------------------------- | | --------- | -------------------------------------------- |
| `v12.2.4` | Support for `fill` property added. |
| `v12.2.0` | Experimental `next/future/image` introduced. | | `v12.2.0` | Experimental `next/future/image` introduced. |
</details> </details>
...@@ -36,7 +37,6 @@ Compared to `next/image`, the new `next/future/image` component has the followin ...@@ -36,7 +37,6 @@ Compared to `next/image`, the new `next/future/image` component has the followin
- Removes `layout`, `objectFit`, and `objectPosition` props in favor of `style` or `className` - Removes `layout`, `objectFit`, and `objectPosition` props in favor of `style` or `className`
- Removes `IntersectionObserver` implementation in favor of [native lazy loading](https://caniuse.com/loading-lazy-attr) - Removes `IntersectionObserver` implementation in favor of [native lazy loading](https://caniuse.com/loading-lazy-attr)
- Removes `loader` config in favor of [`loader`](#loader) prop - Removes `loader` config in favor of [`loader`](#loader) prop
- Note: there is no `fill` mode so `width` & `height` props are required
- Note: the [`onError`](#onerror) prop might behave differently - Note: the [`onError`](#onerror) prop might behave differently
The default layout for `next/image` was `intrinsic`, which would shrink the `width` if the image was larger than it's container. Since no styles are automatically applied to `next/future/image`, you'll need to add the following CSS to achieve the same behavior: The default layout for `next/image` was `intrinsic`, which would shrink the `width` if the image was larger than it's container. Since no styles are automatically applied to `next/future/image`, you'll need to add the following CSS to achieve the same behavior:
...@@ -64,13 +64,13 @@ When using an external URL, you must add it to [domains](#domains) in `next.conf ...@@ -64,13 +64,13 @@ When using an external URL, you must add it to [domains](#domains) in `next.conf
The `width` property represents the _rendered_ width in pixels, so it will affect how large the image appears. The `width` property represents the _rendered_ width in pixels, so it will affect how large the image appears.
Required, except for [statically imported images](/docs/basic-features/image-optimization.md#local-images). Required, except for [statically imported images](/docs/basic-features/image-optimization.md#local-images) or images with the [`fill` property](#fill).
### height ### height
The `height` property represents the _rendered_ height in pixels, so it will affect how large the image appears. The `height` property represents the _rendered_ height in pixels, so it will affect how large the image appears.
Required, except for [statically imported images](/docs/basic-features/image-optimization.md#local-images). Required, except for [statically imported images](/docs/basic-features/image-optimization.md#local-images) or images with the [`fill` property](#fill).
## Optional Props ## Optional Props
...@@ -108,6 +108,22 @@ const MyImage = (props) => { ...@@ -108,6 +108,22 @@ const MyImage = (props) => {
} }
``` ```
### fill
A boolean that causes the image to fill the parent element instead of setting [`width`](#width) and [`height`](#height).
The parent element _must_ assign `position: "relative"`, `position: "fixed"`, or `position: "absolute"` style.
By default, the img element will automatically assign `object-fit: "contain"` and `position: "absolute"` styles.
Optionally, `object-fit` can be assigned any other value such as `object-fit: "cover"`. For this to look correct, the `overflow: "hidden"` style should be assigned to the parent element.
See also:
- [position](https://developer.mozilla.org/en-US/docs/Web/CSS/position)
- [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)
- [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position)
### sizes ### sizes
A string that provides information about how wide the image will be at different breakpoints. A string that provides information about how wide the image will be at different breakpoints.
......
This diff is collapsed.
import React from 'react'
import Image from 'next/future/image'
const Page = () => {
return (
<div>
<h1>Fill Mode</h1>
<div
id="image-container-1"
style={{
height: '300px',
width: '300px',
position: 'relative',
overflow: 'hidden',
}}
>
<Image id="fill-image-1" src="/wide.png" fill />
</div>
<div id="image-container-2">
<Image id="fill-image-2" src="/wide.png" fill />
</div>
<div
id="image-container-3"
style={{
position: 'relative',
overflow: 'hidden',
}}
>
<Image id="fill-image-3" src="/wide.png" fill />
</div>
</div>
)
}
export default Page
import React from 'react'
import Image from 'next/future/image'
const Page = () => {
return (
<div>
<h1>Fill Mode</h1>
<div
id="image-container-1"
style={{
height: '300px',
width: '300px',
position: 'relative',
overflow: 'hidden',
}}
>
<Image id="fill-image-1" src="/wide.png" sizes="300px" fill />
</div>
</div>
)
}
export default Page
import React from 'react'
import Image from 'next/future/image'
const Page = () => {
return (
<div>
<h1>Fill Mode</h1>
<div
id="image-container-1"
style={{
height: '300px',
width: '300px',
position: 'relative',
overflow: 'hidden',
}}
>
<Image
id="fill-image-1"
src="/wide.png"
fill
style={{ position: 'relative' }}
/>
</div>
</div>
)
}
export default Page
import React from 'react'
import Image from 'next/future/image'
const Page = () => {
return (
<div>
<h1>Fill Mode</h1>
<div
id="image-container-1"
style={{
height: '300px',
width: '300px',
position: 'relative',
overflow: 'hidden',
}}
>
<Image
id="fill-image-1"
src="/wide.png"
width="500px"
height="400px"
fill
/>
</div>
</div>
)
}
export default Page
...@@ -677,6 +677,24 @@ function runTests(mode) { ...@@ -677,6 +677,24 @@ function runTests(mode) {
) )
}) })
it('should show error when width prop on fill image', async () => {
const browser = await webdriver(appPort, '/invalid-fill-width')
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toContain(
`Image with src "/wide.png" has both "width" and "fill" properties.`
)
})
it('should show error when CSS position changed on fill image', async () => {
const browser = await webdriver(appPort, '/invalid-fill-position')
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toContain(
`Image with src "/wide.png" has both "fill" and "style.position" properties. Images with "fill" always use position absolute - it cannot be modified.`
)
})
it('should show error when static import and placeholder=blur and blurDataUrl is missing', async () => { it('should show error when static import and placeholder=blur and blurDataUrl is missing', async () => {
const browser = await webdriver( const browser = await webdriver(
appPort, appPort,
...@@ -931,7 +949,62 @@ function runTests(mode) { ...@@ -931,7 +949,62 @@ function runTests(mode) {
await getComputedStyle(browser, 'img-blur', 'background-position') await getComputedStyle(browser, 'img-blur', 'background-position')
).toBe('1px 2px') ).toBe('1px 2px')
}) })
describe('Fill-mode tests', () => {
let browser
beforeAll(async () => {
browser = await webdriver(appPort, '/fill')
})
it('should include a data-attribute on fill images', async () => {
expect(
await browser.elementById('fill-image-1').getAttribute('data-nimg')
).toBe('future-fill')
})
it('should add position:absolute and object-fit to fill images', async () => {
expect(await getComputedStyle(browser, 'fill-image-1', 'position')).toBe(
'absolute'
)
expect(
await getComputedStyle(browser, 'fill-image-1', 'object-fit')
).toBe('contain')
})
it('should add 100% width and height to fill images', async () => {
expect(
await browser.eval(
`document.getElementById("fill-image-1").style.height`
)
).toBe('100%')
expect(
await browser.eval(
`document.getElementById("fill-image-1").style.width`
)
).toBe('100%')
})
if (mode === 'dev') {
it('should not log incorrect warnings', async () => {
await waitFor(1000)
const warnings = (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
expect(warnings).not.toMatch(/Image with src (.*) has "fill"/gm)
})
it('should log warnings when using fill mode incorrectly', async () => {
browser = await webdriver(appPort, '/fill-warnings')
await waitFor(1000)
const warnings = (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
expect(warnings).toContain(
'Image with src "/wide.png" has "fill" and parent element with invalid "position". Provided "static" should be one of absolute,fixed,relative.'
)
expect(warnings).toContain(
'Image with src "/wide.png" has "fill" and a height value of 0. This is likely because the parent element of the image has not been styled to have a set height.'
)
expect(warnings).toContain(
'Image with src "/wide.png" has "fill" but is missing "sizes" prop. Please add it to improve page performance. Read more:'
)
})
}
})
// Tests that use the `unsized` attribute: // Tests that use the `unsized` attribute:
if (mode !== 'dev') { if (mode !== 'dev') {
it('should correctly rotate image', async () => { it('should correctly rotate image', async () => {
......
...@@ -22,6 +22,11 @@ const Page = () => { ...@@ -22,6 +22,11 @@ const Page = () => {
width="500" width="500"
height="500" height="500"
/> />
<Image
id="fill-no-width-and-height"
src="https://image-optimization-test.vercel.app/test.jpg"
fill
/>
<Image <Image
id="quality-num" id="quality-num"
src="https://image-optimization-test.vercel.app/test.jpg" src="https://image-optimization-test.vercel.app/test.jpg"
......
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