Unverified Commit 76bad07b authored by Alex Castle's avatar Alex Castle Committed by GitHub

Add new 'raw' image layout (#34339)

This PR adds a new layout mode for images called `raw`, as discussed with the core team a while back. This mode has the following characteristics:
 - No wrapper `span` around the `img` element
 - No sizer svg
 - Almost no styles automatically added to the `img` element
 - `style` parameter is allowed and is passed through to the underlying `img` element

This also adds documentation changes to describe the new component.

There are a few tradeoffs and DX decisions that may warrant discussion/revision before merging. I'll add a few comments to highlight those issues.

- Related to #18637 
parent 9f54b56b
...@@ -15,7 +15,8 @@ description: Enable Image Optimization with the built-in Image component. ...@@ -15,7 +15,8 @@ description: Enable Image Optimization with the built-in Image component.
<summary><b>Version History</b></summary> <summary><b>Version History</b></summary>
| Version | Changes | | Version | Changes |
| --------- | ------------------------------------------------------------------------------------------------- | | --------- | ----------------------------------------------------------------------------------------------------- |
| `v12.1.1` | `style` prop added. Experimental[\*](#experimental-raw-layout-mode) support for `layout="raw"` added. |
| `v12.1.0` | `dangerouslyAllowSVG` and `contentSecurityPolicy` configuration added. | | `v12.1.0` | `dangerouslyAllowSVG` and `contentSecurityPolicy` configuration added. |
| `v12.0.9` | `lazyRoot` prop added. | | `v12.0.9` | `lazyRoot` prop added. |
| `v12.0.0` | `formats` configuration added.<br/>AVIF support added.<br/>Wrapper `<div>` changed to `<span>`. | | `v12.0.0` | `formats` configuration added.<br/>AVIF support added.<br/>Wrapper `<div>` changed to `<span>`. |
...@@ -65,12 +66,13 @@ The `<Image />` component accepts a number of additional properties beyond those ...@@ -65,12 +66,13 @@ The `<Image />` component accepts a number of additional properties beyond those
The layout behavior of the image as the viewport changes size. The layout behavior of the image as the viewport changes size.
| `layout` | Behavior | `srcSet` | `sizes` | | `layout` | Behavior | `srcSet` | `sizes` | Has wrapper and sizer |
| --------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------- | | ---------------------------------------- | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | -------- | --------------------- |
| `intrinsic` (default) | Scale *down* to fit width of container, up to image size | `1x`, `2x` (based on [imageSizes](#image-sizes)) | N/A | | `intrinsic` (default) | Scale *down* to fit width of container, up to image size | `1x`, `2x` (based on [imageSizes](#image-sizes)) | N/A | yes |
| `fixed` | Sized to `width` and `height` exactly | `1x`, `2x` (based on [imageSizes](#image-sizes)) | N/A | | `fixed` | Sized to `width` and `height` exactly | `1x`, `2x` (based on [imageSizes](#image-sizes)) | N/A | yes |
| `responsive` | Scale to fit width of container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](#image-sizes) and [deviceSizes](#device-sizes)) | `100vw` | | `responsive` | Scale to fit width of container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](#image-sizes) and [deviceSizes](#device-sizes)) | `100vw` | yes |
| `fill` | Grow in both X and Y axes to fill container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](#image-sizes) and [deviceSizes](#device-sizes)) | `100vw` | | `fill` | Grow in both X and Y axes to fill container | `640w`, `750w`, ... `2048w`, `3840w` (based on [imageSizes](#image-sizes) and [deviceSizes](#device-sizes)) | `100vw` | yes |
| `raw`[\*](#experimental-raw-layout-mode) | Insert the image element with no automatic layout behavior | Behaves like `responsive` if the image has the `sizes` prop, and like `fixed` if it does not | optional | no |
- [Demo the `intrinsic` layout (default)](https://image-component.nextjs.gallery/layout-intrinsic) - [Demo the `intrinsic` layout (default)](https://image-component.nextjs.gallery/layout-intrinsic)
- When `intrinsic`, the image will scale the dimensions down for smaller viewports, but maintain the original dimensions for larger viewports. - When `intrinsic`, the image will scale the dimensions down for smaller viewports, but maintain the original dimensions for larger viewports.
...@@ -83,6 +85,9 @@ The layout behavior of the image as the viewport changes size. ...@@ -83,6 +85,9 @@ The layout behavior of the image as the viewport changes size.
- When `fill`, the image will stretch both width and height to the dimensions of the parent element, provided the parent element is relative. - When `fill`, the image will stretch both width and height to the dimensions of the parent element, provided the parent element is relative.
- This is usually paired with the [`objectFit`](#objectFit) property. - This is usually paired with the [`objectFit`](#objectFit) property.
- Ensure the parent element has `position: relative` in their stylesheet. - Ensure the parent element has `position: relative` in their stylesheet.
- When `raw`[\*](#experimental-raw-layout-mode), the image will be rendered as a single image element with no wrappers, sizers or other responsive behavior.
- If your image styling will change the size of a `raw` image, you should include the `sizes` property for proper image serving. Otherwise your image will receive a fixed height and width.
- The other layout modes are optimized for performance and should cover nearly all use cases. It is recommended to try to use those modes before using `raw`.
- [Demo background image](https://image-component.nextjs.gallery/background) - [Demo background image](https://image-component.nextjs.gallery/background)
### loader ### loader
...@@ -121,7 +126,7 @@ const MyImage = (props) => { ...@@ -121,7 +126,7 @@ const MyImage = (props) => {
A string that provides information about how wide the image will be at different breakpoints. Defaults to `100vw` (the full width of the screen) when using `layout="responsive"` or `layout="fill"`. A string that provides information about how wide the image will be at different breakpoints. Defaults to `100vw` (the full width of the screen) when using `layout="responsive"` or `layout="fill"`.
If you are using `layout="fill"` or `layout="responsive"`, it's important to assign `sizes` for any image that takes up less than the full viewport width. If you are using `layout="fill"`, `layout="responsive"`, or `layout="raw"`[\*](#experimental-raw-layout-mode) it's important to assign `sizes` for any image that takes up less than the full viewport width.
For example, when the parent element will constrain the image to always be less than half the viewport width, use `sizes="50vw"`. Without `sizes`, the image will be sent at twice the necessary resolution, decreasing performance. For example, when the parent element will constrain the image to always be less than half the viewport width, use `sizes="50vw"`. Without `sizes`, the image will be sent at twice the necessary resolution, decreasing performance.
...@@ -162,6 +167,12 @@ Try it out: ...@@ -162,6 +167,12 @@ Try it out:
In some cases, you may need more advanced usage. The `<Image />` component optionally accepts the following advanced properties. In some cases, you may need more advanced usage. The `<Image />` component optionally accepts the following advanced properties.
### style
Allows [passing CSS styles](https://reactjs.org/docs/dom-elements.html#style) to the underlying image element.
Note that all `layout` modes other than `"raw"`[\*](#experimental-raw-layout-mode) apply their own styles to the image element, and these automatic styles take precedence over the `style` prop.
### objectFit ### objectFit
Defines how the image will fit into its parent container when using `layout="fill"`. Defines how the image will fit into its parent container when using `layout="fill"`.
...@@ -285,7 +296,6 @@ size, or format. Defaults to `false`. ...@@ -285,7 +296,6 @@ size, or format. Defaults to `false`.
Other properties on the `<Image />` component will be passed to the underlying Other properties on the `<Image />` component will be passed to the underlying
`img` element with the exception of the following: `img` element with the exception of the following:
- `style`. Use `className` instead.
- `srcSet`. Use - `srcSet`. Use
[Device Sizes](#device-sizes) [Device Sizes](#device-sizes)
instead. instead.
...@@ -455,6 +465,24 @@ module.exports = { ...@@ -455,6 +465,24 @@ module.exports = {
} }
``` ```
### Experimental "raw" layout mode
The image component currently supports an additional `layout="raw"` mode, which renders the image without wrappers or styling. This layout mode is currently an experimental feature, while user feedback is gathered. As there is the possibility of breaking changes to the `layout="raw"` interface, the feature is locked behind an experimental feature flag. If you would like to use the `raw` layout mode, you must add the following to your `next.config.js`:
```js
module.exports = {
experimental: {
images: {
layoutRaw: true,
},
},
}
```
> Note on CLS with `layout="raw"`:
> It is possible to cause [layout shift](https://web.dev/cls/) with the image component in `raw` mode. If you include a `sizes` property, the image component will not pass `height` and `width` attributes to the image, to allow you to apply your own responsive sizing.
> An [aspect-ratio](https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio) style property is automatically applied to prevent layout shift, but this won't apply on [older browsers](https://caniuse.com/mdn-css_properties_aspect-ratio).
### Animated Images ### Animated Images
The default [loader](#loader) will automatically bypass Image Optimization for animated images and serve the image as-is. The default [loader](#loader) will automatically bypass Image Optimization for animated images and serve the image as-is.
......
...@@ -181,7 +181,7 @@ The image component has several different [layout modes](/docs/api-reference/nex ...@@ -181,7 +181,7 @@ The image component has several different [layout modes](/docs/api-reference/nex
**Target the image with className, not based on DOM structure** **Target the image with className, not based on DOM structure**
Regardless of the layout mode used, the Image component will have a consistent DOM structure of one `<img>` tag wrapped by exactly one `<span>`. For some modes, it may also have a sibling `<span>` for spacing. These additional `<span>` elements are critical to allow the component to prevent layout shifts. For most layout modes, the Image component will have a DOM structure of one `<img>` tag wrapped by exactly one `<span>`. For some modes, it may also have a sibling `<span>` for spacing. These additional `<span>` elements are critical to allow the component to prevent layout shifts.
The recommended way to style the inner `<img>` is to set the `className` prop on the Image component to the value of an imported [CSS Module](/docs/basic-features/built-in-css-support.md#adding-component-level-css). The value of `className` will be automatically applied to the underlying `<img>` element. The recommended way to style the inner `<img>` is to set the `className` prop on the Image component to the value of an imported [CSS Module](/docs/basic-features/built-in-css-support.md#adding-component-level-css). The value of `className` will be automatically applied to the underlying `<img>` element.
...@@ -189,8 +189,6 @@ Alternatively, you can import a [global stylesheet](/docs/basic-features/built-i ...@@ -189,8 +189,6 @@ Alternatively, you can import a [global stylesheet](/docs/basic-features/built-i
You cannot use [styled-jsx](/docs/basic-features/built-in-css-support.md#css-in-js) because it's scoped to the current component. You cannot use [styled-jsx](/docs/basic-features/built-in-css-support.md#css-in-js) because it's scoped to the current component.
You cannot use the `style` prop because the `<Image>` component does not pass it through to the underlying `<img>`.
**When using `layout='fill'`, the parent element must have `position: relative`** **When using `layout='fill'`, the parent element must have `position: relative`**
This is necessary for the proper rendering of the image element in that layout mode. This is necessary for the proper rendering of the image element in that layout mode.
......
...@@ -1351,6 +1351,7 @@ export default async function getBaseWebpackConfig( ...@@ -1351,6 +1351,7 @@ export default async function getBaseWebpackConfig(
imageSizes: config.images.imageSizes, imageSizes: config.images.imageSizes,
path: config.images.path, path: config.images.path,
loader: config.images.loader, loader: config.images.loader,
experimentalLayoutRaw: config.experimental?.images?.layoutRaw,
...(dev ...(dev
? { ? {
// pass domains in development to allow validating on the client // pass domains in development to allow validating on the client
......
This diff is collapsed.
...@@ -107,6 +107,9 @@ export interface ExperimentalConfig { ...@@ -107,6 +107,9 @@ export interface ExperimentalConfig {
urlImports?: NonNullable<webpack5.Configuration['experiments']>['buildHttp'] urlImports?: NonNullable<webpack5.Configuration['experiments']>['buildHttp']
outputFileTracingRoot?: string outputFileTracingRoot?: string
outputStandalone?: boolean outputStandalone?: boolean
images?: {
layoutRaw: boolean
}
middlewareSourceMaps?: boolean middlewareSourceMaps?: boolean
} }
...@@ -471,6 +474,9 @@ export const defaultConfig: NextConfig = { ...@@ -471,6 +474,9 @@ export const defaultConfig: NextConfig = {
fullySpecified: false, fullySpecified: false,
outputFileTracingRoot: process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT || '', outputFileTracingRoot: process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT || '',
outputStandalone: !!process.env.NEXT_PRIVATE_STANDALONE, outputStandalone: !!process.env.NEXT_PRIVATE_STANDALONE,
images: {
layoutRaw: false,
},
}, },
} }
......
module.exports = {
experimental: {
images: {
layoutRaw: true,
},
},
}
...@@ -15,6 +15,17 @@ export default function Page() { ...@@ -15,6 +15,17 @@ export default function Page() {
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" 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"
/> />
<Image
priority
id="blurry-placeholder-raw"
src="/test.ico"
width="400"
height="400"
layout="raw"
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"
/>
<Image <Image
priority priority
id="blurry-placeholder-tall-centered" id="blurry-placeholder-tall-centered"
......
import React from 'react'
import Image from 'next/image'
import img from '../public/test.jpg'
const Page = () => {
return (
<div>
<Image id="invalid-style" src={img} style={{ width: '100%' }} />
</div>
)
}
export default Page
import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<p>Layout Raw</p>
<div id="image-container1">
<Image
id="raw1"
src="/wide.png"
width="1200"
height="700"
layout="raw"
loading="eager"
></Image>
</div>
<div id="image-container2">
<Image
id="raw2"
src="/wide.png"
width="1200"
height="700"
style={{
paddingLeft: '4rem',
width: '100%',
objectPosition: '30% 30%',
}}
layout="raw"
sizes="50vh"
></Image>
</div>
<div id="image-container3">
<Image
id="raw3"
src="/test.png"
width="400"
height="400"
layout="raw"
loading="eager"
></Image>
</div>
</div>
)
}
export default Page
...@@ -84,6 +84,16 @@ const Page = () => { ...@@ -84,6 +84,16 @@ const Page = () => {
idToCount={idToCount} idToCount={idToCount}
setIdToCount={setIdToCount} setIdToCount={setIdToCount}
/> />
<ImageWithMessage
id="9"
src={require('../public/test.png')}
placeholder="blur"
layout="raw"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<button id="toggle" onClick={() => setClicked(!clicked)}> <button id="toggle" onClick={() => setClicked(!clicked)}>
Toggle Toggle
</button> </button>
......
...@@ -35,6 +35,14 @@ const Page = () => { ...@@ -35,6 +35,14 @@ const Page = () => {
height="700" height="700"
layout="responsive" layout="responsive"
/> />
<Image
priority
id="raw"
src="/test.webp"
width="1200"
height="700"
layout="raw"
/>
<p id="stubtext">This is the priority page</p> <p id="stubtext">This is the priority page</p>
</div> </div>
) )
......
import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<h1>Style prop usage and warnings</h1>
<Image
layout="fixed"
id="with-styles"
src="/test.png"
width={400}
height={400}
style={{ borderRadius: '10px', padding: 10 }}
loading="eager"
/>
<Image
layout="intrinsic"
id="with-overlapping-styles-intrinsic"
src="/test.jpg"
width={400}
height={400}
style={{ width: '10px', borderRadius: '10px', margin: '15px' }}
loading="eager"
/>
<Image
layout="raw"
id="with-overlapping-styles-raw"
src="/test.webp"
width={400}
height={400}
style={{ width: '10px', borderRadius: '10px', margin: '15px' }}
loading="eager"
/>
<Image
layout="responsive"
id="without-styles-responsive"
src="/test.webp"
width={400}
height={400}
loading="eager"
/>
<Image
layout="raw"
id="without-styles-raw"
src="/test.webp"
width={400}
height={400}
loading="eager"
/>
</div>
)
}
export default Page
...@@ -135,6 +135,11 @@ function runTests(mode) { ...@@ -135,6 +135,11 @@ function runTests(mode) {
imagesrcset: imagesrcset:
'/_next/image?url=%2Fwide.png&w=640&q=75 640w, /_next/image?url=%2Fwide.png&w=750&q=75 750w, /_next/image?url=%2Fwide.png&w=828&q=75 828w, /_next/image?url=%2Fwide.png&w=1080&q=75 1080w, /_next/image?url=%2Fwide.png&w=1200&q=75 1200w, /_next/image?url=%2Fwide.png&w=1920&q=75 1920w, /_next/image?url=%2Fwide.png&w=2048&q=75 2048w, /_next/image?url=%2Fwide.png&w=3840&q=75 3840w', '/_next/image?url=%2Fwide.png&w=640&q=75 640w, /_next/image?url=%2Fwide.png&w=750&q=75 750w, /_next/image?url=%2Fwide.png&w=828&q=75 828w, /_next/image?url=%2Fwide.png&w=1080&q=75 1080w, /_next/image?url=%2Fwide.png&w=1200&q=75 1200w, /_next/image?url=%2Fwide.png&w=1920&q=75 1920w, /_next/image?url=%2Fwide.png&w=2048&q=75 2048w, /_next/image?url=%2Fwide.png&w=3840&q=75 3840w',
}, },
{
imagesizes: '',
imagesrcset:
'/_next/image?url=%2Ftest.webp&w=1200&q=75 1x, /_next/image?url=%2Ftest.webp&w=3840&q=75 2x',
},
]) ])
const warnings = (await browser.log('browser')) const warnings = (await browser.log('browser'))
...@@ -273,6 +278,10 @@ function runTests(mode) { ...@@ -273,6 +278,10 @@ function runTests(mode) {
() => browser.eval(`document.getElementById("img8").currentSrc`), () => browser.eval(`document.getElementById("img8").currentSrc`),
/test-rect.jpg/ /test-rect.jpg/
) )
await check(
() => browser.eval(`document.getElementById("msg9").textContent`),
'loaded 1 img9 with dimensions 400x400'
)
} finally { } finally {
if (browser) { if (browser) {
await browser.close() await browser.close()
...@@ -584,6 +593,101 @@ function runTests(mode) { ...@@ -584,6 +593,101 @@ function runTests(mode) {
} }
}) })
it('should render no wrappers or sizers and minimal styling with layout-raw', async () => {
let browser
try {
browser = await webdriver(appPort, '/layout-raw')
const numberOfChildren = await browser.eval(
`document.getElementById('image-container1').children.length`
)
expect(numberOfChildren).toBe(1)
const childElementType = await browser.eval(
`document.getElementById('image-container1').children[0].nodeName`
)
expect(childElementType).toBe('IMG')
expect(await browser.elementById('raw1').getAttribute('style')).toBe(
`aspect-ratio:1200 / 700`
)
expect(await browser.elementById('raw1').getAttribute('srcset')).toBe(
`/_next/image?url=%2Fwide.png&w=1200&q=75 1x, /_next/image?url=%2Fwide.png&w=3840&q=75 2x`
)
expect(await browser.elementById('raw2').getAttribute('style')).toBe(
'padding-left:4rem;width:100%;object-position:30% 30%;aspect-ratio:1200 / 700'
)
expect(await browser.elementById('raw2').getAttribute('srcset')).toBe(
`/_next/image?url=%2Fwide.png&w=16&q=75 16w, /_next/image?url=%2Fwide.png&w=32&q=75 32w, /_next/image?url=%2Fwide.png&w=48&q=75 48w, /_next/image?url=%2Fwide.png&w=64&q=75 64w, /_next/image?url=%2Fwide.png&w=96&q=75 96w, /_next/image?url=%2Fwide.png&w=128&q=75 128w, /_next/image?url=%2Fwide.png&w=256&q=75 256w, /_next/image?url=%2Fwide.png&w=384&q=75 384w, /_next/image?url=%2Fwide.png&w=640&q=75 640w, /_next/image?url=%2Fwide.png&w=750&q=75 750w, /_next/image?url=%2Fwide.png&w=828&q=75 828w, /_next/image?url=%2Fwide.png&w=1080&q=75 1080w, /_next/image?url=%2Fwide.png&w=1200&q=75 1200w, /_next/image?url=%2Fwide.png&w=1920&q=75 1920w, /_next/image?url=%2Fwide.png&w=2048&q=75 2048w, /_next/image?url=%2Fwide.png&w=3840&q=75 3840w`
)
expect(await browser.elementById('raw3').getAttribute('style')).toBe(
'aspect-ratio:400 / 400'
)
expect(await browser.elementById('raw3').getAttribute('srcset')).toBe(
`/_next/image?url=%2Ftest.png&w=640&q=75 1x, /_next/image?url=%2Ftest.png&w=828&q=75 2x`
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should handle the styles prop appropriately', async () => {
let browser
try {
browser = await webdriver(appPort, '/style-prop')
expect(
await browser.elementById('with-styles').getAttribute('style')
).toBe(
'border-radius:10px;padding:0;position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%'
)
expect(
await browser
.elementById('with-overlapping-styles-intrinsic')
.getAttribute('style')
).toBe(
'width:0;border-radius:10px;margin:auto;position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;display:block;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%'
)
expect(
await browser
.elementById('with-overlapping-styles-raw')
.getAttribute('style')
).toBe('width:10px;border-radius:10px;margin:15px;aspect-ratio:400 / 400')
expect(
await browser
.elementById('without-styles-responsive')
.getAttribute('style')
).toBe(
'position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%'
)
expect(
await browser.elementById('without-styles-raw').getAttribute('style')
).toBe('aspect-ratio:400 / 400')
if (mode === 'dev') {
await waitFor(1000)
const warnings = (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
expect(warnings).toMatch(
/Image with src \/test.png is assigned the following styles, which are overwritten by automatically-generated styles: padding/gm
)
expect(warnings).toMatch(
/Image with src \/test.jpg is assigned the following styles, which are overwritten by automatically-generated styles: width, margin/gm
)
expect(warnings).not.toMatch(
/Image with src \/test.webp is assigned the following styles/gm
)
}
} 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')
...@@ -690,18 +794,6 @@ function runTests(mode) { ...@@ -690,18 +794,6 @@ function runTests(mode) {
) )
}) })
it('should warn when style prop is used', async () => {
const browser = await webdriver(appPort, '/invalid-style')
await check(async () => {
return (await browser.log('browser'))
.map((log) => log.message)
.join('\n')
}, /Image with src (.*)jpg(.*) is using unsupported "style" property(.*)/gm)
expect(await hasRedbox(browser)).toBe(false)
})
it('should not warn when Image is child of p', async () => { it('should not warn when Image is child of p', async () => {
const browser = await webdriver(appPort, '/inside-paragraph') const browser = await webdriver(appPort, '/inside-paragraph')
...@@ -831,6 +923,7 @@ function runTests(mode) { ...@@ -831,6 +923,7 @@ function runTests(mode) {
} }
return 'done' return 'done'
}, 'done') }, 'done')
await waitFor(1000)
const warnings = (await browser.log('browser')) const warnings = (await browser.log('browser'))
.map((log) => log.message) .map((log) => log.message)
.filter((log) => log.startsWith('Image with src')) .filter((log) => log.startsWith('Image with src'))
...@@ -1001,6 +1094,10 @@ function runTests(mode) { ...@@ -1001,6 +1094,10 @@ function runTests(mode) {
`background-image:url("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")` `background-image:url("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")`
) )
expect($html('#blurry-placeholder-raw')[0].attribs.style).toContain(
`background-image:url("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")`
)
expect($html('#blurry-placeholder')[0].attribs.style).toContain( expect($html('#blurry-placeholder')[0].attribs.style).toContain(
`background-position:0% 0%` `background-position:0% 0%`
) )
...@@ -1039,6 +1136,15 @@ function runTests(mode) { ...@@ -1039,6 +1136,15 @@ function runTests(mode) {
), ),
'none' 'none'
) )
await check(
async () =>
await getComputedStyle(
browser,
'blurry-placeholder-raw',
'background-image'
),
'none'
)
expect( expect(
await getComputedStyle( await getComputedStyle(
browser, browser,
......
module.exports = {
images: {
domains: ['via.placeholder.com'],
},
}
import React from 'react'
import Image from 'next/image'
const Invalid = () => {
return (
<div>
<h1>Invalid TS</h1>
<Image
width={500}
height={500}
src="https://via.placeholder.com/500"
style={{ objectFit: 'cover' }}
></Image>
<p id="stubtext">This is the invalid usage</p>
</div>
)
}
export default Invalid
/* eslint-env jest */
import { nextBuild } from 'next-test-utils'
import { join } from 'path'
const appDir = join(__dirname, '..')
describe('TypeScript Image Component with Styles', () => {
describe('next build', () => {
it('should fail to build when the `style` prop is passed to <Image />', async () => {
const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).toMatch(/Failed to compile/)
expect(stderr).toMatch(/Property 'style' does not exist on type/)
expect(code).toBe(1)
})
})
})
{
"compilerOptions": {
"esModuleInterop": true,
"module": "esnext",
"jsx": "preserve",
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true
},
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "components", "pages"]
}
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