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
- `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.
- `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).
- `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)
......
......@@ -13,6 +13,14 @@ const loaders = new Map<LoaderKey, (props: LoaderProps) => string>([
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 = {
deviceSizes: number[]
imageSizes: number[]
......@@ -29,6 +37,7 @@ type ImageProps = Omit<
quality?: number | string
priority?: boolean
loading?: LoadingValue
layout?: LayoutValue
unoptimized?: boolean
} & (
| { width: number | string; height: number | string; unsized?: false }
......@@ -201,6 +210,7 @@ export default function Image({
unoptimized = false,
priority = false,
loading,
layout,
className,
quality,
width,
......@@ -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)) {
throw new Error(
`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({
}
}
if (!layout) {
if (sizes) {
layout = 'responsive'
} else {
layout = 'intrinsic'
}
}
let lazy = loading === 'lazy'
if (!priority && typeof loading === 'undefined') {
lazy = true
......@@ -265,25 +290,41 @@ export default function Image({
const heightInt = getInt(height)
const qualityInt = getInt(quality)
let divStyle: React.CSSProperties | undefined
let imgStyle: React.CSSProperties | undefined
let wrapperStyle: React.CSSProperties | undefined
let sizerStyle: React.CSSProperties | undefined
let sizerSvg: string | undefined
let imgStyle: React.CSSProperties | undefined
if (
typeof widthInt !== 'undefined' &&
typeof heightInt !== 'undefined' &&
!unsized
) {
// <Image src="i.png" width={100} height={100} />
// <Image src="i.png" width="100" height="100" />
const quotient = heightInt / widthInt
const ratio = isNaN(quotient) ? 1 : quotient * 100
wrapperStyle = {
maxWidth: '100%',
width: widthInt,
}
divStyle = {
position: 'relative',
paddingBottom: `${ratio}%`,
const paddingTop = isNaN(quotient) ? '100%' : `${quotient * 100}%`
if (layout === 'responsive') {
// <Image src="i.png" width="100" height="100" layout="responsive" />
wrapperStyle = { position: 'relative' }
sizerStyle = { paddingTop }
} else if (layout === 'intrinsic') {
// <Image src="i.png" width="100" height="100" layout="intrinsic" />
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 = {
visibility: lazy ? 'hidden' : 'visible',
......@@ -357,25 +398,37 @@ export default function Image({
return (
<div style={wrapperStyle}>
<div style={divStyle}>
{shouldPreload
? generatePreload({
src,
width: widthInt,
unoptimized,
sizes,
quality: qualityInt,
})
: ''}
<img
{...rest}
{...imgAttributes}
className={className}
sizes={sizes}
ref={thisEl}
style={imgStyle}
/>
</div>
{shouldPreload
? generatePreload({
src,
width: widthInt,
unoptimized,
sizes,
quality: qualityInt,
})
: null}
{sizerStyle ? (
<div style={sizerStyle}>
{sizerSvg ? (
<img
style={{ maxWidth: '100%', display: 'block' }}
alt=""
aria-hidden={true}
role="presentation"
src={`data:image/svg+xml;charset=utf-8,${sizerSvg}`}
/>
) : null}
</div>
) : null}
<img
{...rest}
{...imgAttributes}
decoding="async"
className={className}
sizes={sizes}
ref={thisEl}
style={imgStyle}
/>
</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) {
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) {
it('should load the images', async () => {
let browser
try {
browser = await webdriver(appPort, '/')
await check(async () => {
const result = await browser.eval(
`document.getElementById('basic-image').naturalWidth`
......@@ -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') {
it('should show missing src error', async () => {
const browser = await webdriver(appPort, '/missing-src')
......
......@@ -17,6 +17,7 @@ interface Chain {
back: () => Chain
forward: () => Chain
refresh: () => Chain
setDimensions: (opts: { height: number; width: number }) => Chain
close: () => Chain
quit: () => Chain
}
......
......@@ -126,6 +126,12 @@ export default class Chain {
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() {
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