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

Add layout prop to Image component (#18491)

This PR introduces a new `layout` property.

This allows 3 possible values (`fixed`, `intrinsic`, or `responsive`) which solve many use cases we have seen since 10.0.0 and will hopefully avoid usage of `unsized`.

Fixes #18351 
Co-authored-by: 's avatarJoe Haddad <joe.haddad@zeit.co>
parent 42633188
...@@ -48,6 +48,7 @@ export default Home ...@@ -48,6 +48,7 @@ export default Home
- `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 `unsized` is true.
- `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 `unsized` is true.
- `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`.
- `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)
......
...@@ -13,6 +13,14 @@ const loaders = new Map<LoaderKey, (props: LoaderProps) => string>([ ...@@ -13,6 +13,14 @@ const loaders = new Map<LoaderKey, (props: LoaderProps) => string>([
type LoaderKey = 'imgix' | 'cloudinary' | 'akamai' | 'default' type LoaderKey = 'imgix' | 'cloudinary' | 'akamai' | 'default'
const VALID_LAYOUT_VALUES = [
'fixed',
'intrinsic',
'responsive',
undefined,
] as const
type LayoutValue = typeof VALID_LAYOUT_VALUES[number]
type ImageData = { type ImageData = {
deviceSizes: number[] deviceSizes: number[]
imageSizes: number[] imageSizes: number[]
...@@ -29,6 +37,7 @@ type ImageProps = Omit< ...@@ -29,6 +37,7 @@ 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?: false }
...@@ -201,6 +210,7 @@ export default function Image({ ...@@ -201,6 +210,7 @@ export default function Image({
unoptimized = false, unoptimized = false,
priority = false, priority = false,
loading, loading,
layout,
className, className,
quality, quality,
width, width,
...@@ -218,6 +228,13 @@ export default function Image({ ...@@ -218,6 +228,13 @@ export default function Image({
)}` )}`
) )
} }
if (!VALID_LAYOUT_VALUES.includes(layout)) {
throw new Error(
`Image with src "${src}" has invalid "layout" property. Provided "${layout}" should be one of ${VALID_LAYOUT_VALUES.map(
String
).join(',')}.`
)
}
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(
...@@ -232,6 +249,14 @@ export default function Image({ ...@@ -232,6 +249,14 @@ export default function Image({
} }
} }
if (!layout) {
if (sizes) {
layout = 'responsive'
} else {
layout = 'intrinsic'
}
}
let lazy = loading === 'lazy' let lazy = loading === 'lazy'
if (!priority && typeof loading === 'undefined') { if (!priority && typeof loading === 'undefined') {
lazy = true lazy = true
...@@ -265,25 +290,41 @@ export default function Image({ ...@@ -265,25 +290,41 @@ export default function Image({
const heightInt = getInt(height) const heightInt = getInt(height)
const qualityInt = getInt(quality) const qualityInt = getInt(quality)
let divStyle: React.CSSProperties | undefined
let imgStyle: React.CSSProperties | undefined
let wrapperStyle: React.CSSProperties | undefined let wrapperStyle: React.CSSProperties | undefined
let sizerStyle: React.CSSProperties | undefined
let sizerSvg: string | undefined
let imgStyle: React.CSSProperties | undefined
if ( if (
typeof widthInt !== 'undefined' && typeof widthInt !== 'undefined' &&
typeof heightInt !== '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" />
const quotient = heightInt / widthInt const quotient = heightInt / widthInt
const ratio = isNaN(quotient) ? 1 : quotient * 100 const paddingTop = isNaN(quotient) ? '100%' : `${quotient * 100}%`
wrapperStyle = { if (layout === 'responsive') {
maxWidth: '100%', // <Image src="i.png" width="100" height="100" layout="responsive" />
width: widthInt, wrapperStyle = { position: 'relative' }
} sizerStyle = { paddingTop }
divStyle = { } else if (layout === 'intrinsic') {
position: 'relative', // <Image src="i.png" width="100" height="100" layout="intrinsic" />
paddingBottom: `${ratio}%`, wrapperStyle = {
display: 'inline-block',
position: 'relative',
maxWidth: '100%',
}
sizerStyle = {
maxWidth: '100%',
}
sizerSvg = `<svg width="${widthInt}" height="${heightInt}" xmlns="http://www.w3.org/2000/svg" version="1.1"/>`
} else if (layout === 'fixed') {
// <Image src="i.png" width="100" height="100" layout="fixed" />
wrapperStyle = {
display: 'inline-block',
position: 'relative',
width: widthInt,
height: heightInt,
}
} }
imgStyle = { imgStyle = {
visibility: lazy ? 'hidden' : 'visible', visibility: lazy ? 'hidden' : 'visible',
...@@ -357,25 +398,37 @@ export default function Image({ ...@@ -357,25 +398,37 @@ export default function Image({
return ( return (
<div style={wrapperStyle}> <div style={wrapperStyle}>
<div style={divStyle}> {shouldPreload
{shouldPreload ? generatePreload({
? generatePreload({ src,
src, width: widthInt,
width: widthInt, unoptimized,
unoptimized, sizes,
sizes, quality: qualityInt,
quality: qualityInt, })
}) : null}
: ''} {sizerStyle ? (
<img <div style={sizerStyle}>
{...rest} {sizerSvg ? (
{...imgAttributes} <img
className={className} style={{ maxWidth: '100%', display: 'block' }}
sizes={sizes} alt=""
ref={thisEl} aria-hidden={true}
style={imgStyle} role="presentation"
/> src={`data:image/svg+xml;charset=utf-8,${sizerSvg}`}
</div> />
) : null}
</div>
) : null}
<img
{...rest}
{...imgAttributes}
decoding="async"
className={className}
sizes={sizes}
ref={thisEl}
style={imgStyle}
/>
</div> </div>
) )
} }
......
import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<p>Layout Fixed</p>
<Image
id="fixed1"
src="/wide.png"
width="1200"
height="700"
layout="fixed"
></Image>
<Image
id="fixed2"
src="/wide.png"
width="1200"
height="700"
layout="fixed"
></Image>
<Image
id="fixed3"
src="/wide.png"
width="1200"
height="700"
layout="fixed"
></Image>
<Image
id="fixed4"
src="/wide.png"
width="1200"
height="700"
layout="fixed"
></Image>
<p>Layout Fixed</p>
</div>
)
}
export default Page
import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<p>Layout Intrinsic</p>
<Image
id="intrinsic1"
src="/wide.png"
width="1200"
height="700"
layout="intrinsic"
></Image>
<Image
id="intrinsic2"
src="/wide.png"
width="1200"
height="700"
layout="intrinsic"
></Image>
<Image
id="intrinsic3"
src="/wide.png"
width="1200"
height="700"
layout="intrinsic"
></Image>
<Image
id="intrinsic4"
src="/wide.png"
width="1200"
height="700"
layout="intrinsic"
></Image>
<p>Layout Intrinsic</p>
</div>
)
}
export default Page
import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<p>Layout Responsive</p>
<Image
id="responsive1"
src="/wide.png"
width="1200"
height="700"
layout="responsive"
></Image>
<Image
id="responsive2"
src="/wide.png"
width="1200"
height="700"
layout="responsive"
></Image>
<Image
id="responsive3"
src="/wide.png"
width="1200"
height="700"
layout="responsive"
></Image>
<Image
id="responsive4"
src="/wide.png"
width="1200"
height="700"
layout="responsive"
></Image>
<p>Layout Responsive</p>
</div>
)
}
export default Page
...@@ -35,11 +35,26 @@ async function hasImageMatchingUrl(browser, url) { ...@@ -35,11 +35,26 @@ async function hasImageMatchingUrl(browser, url) {
return foundMatch return foundMatch
} }
async function getComputed(browser, id, prop) {
const style = await browser.eval(
`getComputedStyle(document.getElementById('${id}')).${prop}`
)
if (typeof style === 'string') {
return parseInt(style.replace(/px$/, ''), 10)
}
return null
}
function getRatio(width, height) {
return Math.round((height / width) * 1000)
}
function runTests(mode) { function runTests(mode) {
it('should load the images', async () => { it('should load the images', async () => {
let browser let browser
try { try {
browser = await webdriver(appPort, '/') browser = await webdriver(appPort, '/')
await check(async () => { await check(async () => {
const result = await browser.eval( const result = await browser.eval(
`document.getElementById('basic-image').naturalWidth` `document.getElementById('basic-image').naturalWidth`
...@@ -102,6 +117,93 @@ function runTests(mode) { ...@@ -102,6 +117,93 @@ function runTests(mode) {
} }
}) })
it('should work with layout-fixed so resizing window does not resize image', async () => {
let browser
try {
browser = await webdriver(appPort, '/layout-fixed')
const width = 1200
const height = 700
const delta = 250
const id = 'fixed1'
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,
})
expect(await getComputed(browser, id, 'width')).toBe(width)
expect(await getComputed(browser, id, 'height')).toBe(height)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should work with layout-intrinsic so resizing window maintains image aspect ratio', async () => {
let browser
try {
browser = await webdriver(appPort, '/layout-intrinsic')
const width = 1200
const height = 700
const delta = 250
const id = 'intrinsic1'
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).toBeLessThan(width)
expect(newHeight).toBeLessThan(height)
expect(getRatio(newWidth, newHeight)).toBe(getRatio(width, height))
} finally {
if (browser) {
await browser.close()
}
}
})
it('should work with layout-responsive so resizing window maintains image aspect ratio', async () => {
let browser
try {
browser = await webdriver(appPort, '/layout-responsive')
const width = 1200
const height = 700
const delta = 250
const id = 'responsive1'
await browser.setDimensions({
width: width + delta,
height: height + delta,
})
expect(await getComputed(browser, id, 'width')).toBeGreaterThan(width)
expect(await getComputed(browser, id, 'height')).toBeGreaterThan(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).toBeLessThan(width)
expect(newHeight).toBeLessThan(height)
expect(getRatio(newWidth, newHeight)).toBe(getRatio(width, height))
} 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')
......
...@@ -17,6 +17,7 @@ interface Chain { ...@@ -17,6 +17,7 @@ interface Chain {
back: () => Chain back: () => Chain
forward: () => Chain forward: () => Chain
refresh: () => Chain refresh: () => Chain
setDimensions: (opts: { height: number; width: number }) => Chain
close: () => Chain close: () => Chain
quit: () => Chain quit: () => Chain
} }
......
...@@ -126,6 +126,12 @@ export default class Chain { ...@@ -126,6 +126,12 @@ export default class Chain {
return this.updateChain(() => this.browser.navigate().refresh()) return this.updateChain(() => this.browser.navigate().refresh())
} }
setDimensions({ height, width }) {
return this.updateChain(() =>
this.browser.manage().window().setRect({ width, height, x: 0, y: 0 })
)
}
close() { close() {
return this.updateChain(() => Promise.resolve()) return this.updateChain(() => Promise.resolve())
} }
......
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