Unverified Commit 241195dd authored by Steven's avatar Steven Committed by GitHub

BREAKING CHANGE: Rename `next/image` to `next/legacy/image` & rename…

BREAKING CHANGE: Rename `next/image` to `next/legacy/image` & rename `next/future/image` to `next/image` (#41399)

This PR introduces breaking changes by renaming components.

- Rename `next/image` to `next/legacy/image`
- Rename `next/future/image` to `next/image`

The diff is very confusing because both components are very similar so git got confused.
parent 560e93ef
......@@ -1067,7 +1067,7 @@ export default async function getBaseWebpackConfig(
}
const notExternalModules =
/^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|document|link|image|future\/image|constants|dynamic|script|navigation|headers)$)|string-hash|private-next-rsc-mod-ref-proxy$)/
/^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|document|link|image|legacy\/image|constants|dynamic|script|navigation|headers)$)|string-hash|private-next-rsc-mod-ref-proxy$)/
if (notExternalModules.test(request)) {
return
}
......
......@@ -21,6 +21,7 @@ export type SWC_TARGET_TRIPLE =
export type Feature =
| 'next/image'
| 'next/future/image'
| 'next/legacy/image'
| 'next/script'
| 'next/dynamic'
| 'swcLoader'
......@@ -58,6 +59,7 @@ interface Connection {
const FEATURE_MODULE_MAP: ReadonlyMap<Feature, string> = new Map([
['next/image', '/next/image.js'],
['next/future/image', '/next/future/image.js'],
['next/legacy/image', '/next/legacy/image.js'],
['next/script', '/next/script.js'],
['next/dynamic', '/next/dynamic.js'],
])
......
......@@ -9,30 +9,20 @@ import React, {
useState,
} from 'react'
import Head from '../shared/lib/head'
import { getImageBlurSvg } from '../shared/lib/image-blur-svg'
import {
ImageConfigComplete,
imageConfigDefault,
LoaderValue,
VALID_LOADERS,
} from '../shared/lib/image-config'
import { useIntersection } from './use-intersection'
import { ImageConfigContext } from '../shared/lib/image-config-context'
import { warnOnce } from '../shared/lib/utils'
import { normalizePathTrailingSlash } from './normalize-trailing-slash'
function normalizeSrc(src: string): string {
return src[0] === '/' ? src.slice(1) : src
}
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete
const loadedImageURLs = new Set<string>()
const allImgs = new Map<
string,
{ src: string; priority: boolean; placeholder: string }
>()
let perfObserver: PerformanceObserver | undefined
const emptyDataURL =
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
if (typeof window === 'undefined') {
;(global as any).__NEXT_IMAGE_IMPORTED = true
......@@ -41,7 +31,7 @@ if (typeof window === 'undefined') {
const VALID_LOADING_VALUES = ['lazy', 'eager', undefined] as const
type LoadingValue = typeof VALID_LOADING_VALUES[number]
type ImageConfig = ImageConfigComplete & { allSizes: number[] }
export type ImageLoader = (resolverProps: ImageLoaderProps) => string
export type ImageLoader = (p: ImageLoaderProps) => string
export type ImageLoaderProps = {
src: string
......@@ -52,152 +42,14 @@ export type ImageLoaderProps = {
// Do not export - this is an internal type only
// because `next.config.js` is only meant for the
// built-in loaders, not for a custom loader() prop.
type ImageLoaderWithConfig = (
resolverProps: ImageLoaderPropsWithConfig
) => string
type ImageLoaderWithConfig = (p: ImageLoaderPropsWithConfig) => string
type ImageLoaderPropsWithConfig = ImageLoaderProps & {
config: Readonly<ImageConfig>
}
function imgixLoader({
config,
src,
width,
quality,
}: ImageLoaderPropsWithConfig): string {
// Demo: https://static.imgix.net/daisy.png?auto=format&fit=max&w=300
const url = new URL(`${config.path}${normalizeSrc(src)}`)
const params = url.searchParams
// auto params can be combined with comma separation, or reiteration
params.set('auto', params.getAll('auto').join(',') || 'format')
params.set('fit', params.get('fit') || 'max')
params.set('w', params.get('w') || width.toString())
if (quality) {
params.set('q', quality.toString())
}
return url.href
}
function akamaiLoader({
config,
src,
width,
}: ImageLoaderPropsWithConfig): string {
return `${config.path}${normalizeSrc(src)}?imwidth=${width}`
}
function cloudinaryLoader({
config,
src,
width,
quality,
}: ImageLoaderPropsWithConfig): string {
// Demo: https://res.cloudinary.com/demo/image/upload/w_300,c_limit,q_auto/turtles.jpg
const params = ['f_auto', 'c_limit', 'w_' + width, 'q_' + (quality || 'auto')]
const paramsString = params.join(',') + '/'
return `${config.path}${paramsString}${normalizeSrc(src)}`
}
function customLoader({ src }: ImageLoaderProps): string {
throw new Error(
`Image with src "${src}" is missing "loader" prop.` +
`\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader`
)
}
function defaultLoader({
config,
src,
width,
quality,
}: ImageLoaderPropsWithConfig): string {
if (process.env.NODE_ENV !== 'production') {
const missingValues = []
// these should always be provided but make sure they are
if (!src) missingValues.push('src')
if (!width) missingValues.push('width')
if (missingValues.length > 0) {
throw new Error(
`Next Image Optimization requires ${missingValues.join(
', '
)} to be provided. Make sure you pass them as props to the \`next/image\` component. Received: ${JSON.stringify(
{ src, width, quality }
)}`
)
}
if (src.startsWith('//')) {
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)`
)
}
if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
let parsedSrc: URL
try {
parsedSrc = new URL(src)
} catch (err) {
console.error(err)
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://)`
)
}
if (process.env.NODE_ENV !== 'test') {
// We use dynamic require because this should only error in development
const { hasMatch } = require('../shared/lib/match-remote-pattern')
if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
)
}
}
}
}
if (src.endsWith('.svg') && !config.dangerouslyAllowSVG) {
// Special case to make svg serve as-is to avoid proxying
// through the built-in Image Optimization API.
return src
}
return `${normalizePathTrailingSlash(config.path)}?url=${encodeURIComponent(
src
)}&w=${width}&q=${quality || 75}`
}
const loaders = new Map<
LoaderValue,
(props: ImageLoaderPropsWithConfig) => string
>([
['default', defaultLoader],
['imgix', imgixLoader],
['cloudinary', cloudinaryLoader],
['akamai', akamaiLoader],
['custom', customLoader],
])
const VALID_LAYOUT_VALUES = [
'fill',
'fixed',
'intrinsic',
'responsive',
undefined,
] as const
type LayoutValue = typeof VALID_LAYOUT_VALUES[number]
type PlaceholderValue = 'blur' | 'empty'
type OnLoadingComplete = (result: {
naturalWidth: number
naturalHeight: number
}) => void
type OnLoad = React.ReactEventHandler<HTMLImageElement> | undefined
type OnLoadingComplete = (img: HTMLImageElement) => void
type ImgElementStyle = NonNullable<JSX.IntrinsicElements['img']['style']>
......@@ -210,6 +62,8 @@ export interface StaticImageData {
height: number
width: number
blurDataURL?: string
blurWidth?: number
blurHeight?: number
}
interface StaticRequire {
......@@ -242,55 +96,50 @@ function isStaticImport(src: string | StaticImport): src is StaticImport {
export type ImageProps = Omit<
JSX.IntrinsicElements['img'],
'src' | 'srcSet' | 'ref' | 'width' | 'height' | 'loading'
'src' | 'srcSet' | 'ref' | 'alt' | 'width' | 'height' | 'loading'
> & {
src: string | StaticImport
alt: string
width?: SafeNumber
height?: SafeNumber
layout?: LayoutValue
fill?: boolean
loader?: ImageLoader
quality?: SafeNumber
priority?: boolean
loading?: LoadingValue
lazyRoot?: React.RefObject<HTMLElement> | null
lazyBoundary?: string
placeholder?: PlaceholderValue
blurDataURL?: string
unoptimized?: boolean
objectFit?: ImgElementStyle['objectFit']
objectPosition?: ImgElementStyle['objectPosition']
onLoadingComplete?: OnLoadingComplete
}
type ImageElementProps = Omit<ImageProps, 'src' | 'loader'> & {
type ImageElementProps = Omit<ImageProps, 'src' | 'alt' | 'loader'> & {
srcString: string
imgAttributes: GenImgAttrsResult
heightInt: number | undefined
widthInt: number | undefined
qualityInt: number | undefined
layout: LayoutValue
imgStyle: ImgElementStyle
blurStyle: ImgElementStyle
isLazy: boolean
fill?: boolean
loading: LoadingValue
config: ImageConfig
unoptimized: boolean
loader: ImageLoaderWithConfig
placeholder: PlaceholderValue
onLoadRef: React.MutableRefObject<OnLoad | undefined>
onLoadingCompleteRef: React.MutableRefObject<OnLoadingComplete | undefined>
setBlurComplete: (b: boolean) => void
setIntersection: (img: HTMLImageElement | null) => void
isVisible: boolean
noscriptSizes: string | undefined
setShowAltText: (b: boolean) => void
}
function getWidths(
{ deviceSizes, allSizes }: ImageConfig,
width: number | undefined,
layout: LayoutValue,
sizes: string | undefined
): { widths: number[]; kind: 'w' | 'x' } {
if (sizes && (layout === 'fill' || layout === 'responsive')) {
if (sizes) {
// Find all the "vw" percent sizes used in the sizes prop
const viewportWidthRe = /(^|\s)(1?\d?\d)vw/g
const percentSizes = []
......@@ -306,11 +155,7 @@ function getWidths(
}
return { widths: allSizes, kind: 'w' }
}
if (
typeof width !== 'number' ||
layout === 'fill' ||
layout === 'responsive'
) {
if (typeof width !== 'number') {
return { widths: deviceSizes, kind: 'w' }
}
......@@ -336,7 +181,6 @@ type GenImgAttrsData = {
config: ImageConfig
src: string
unoptimized: boolean
layout: LayoutValue
loader: ImageLoaderWithConfig
width?: number
quality?: number
......@@ -353,7 +197,6 @@ function generateImgAttrs({
config,
src,
unoptimized,
layout,
width,
quality,
sizes,
......@@ -363,7 +206,7 @@ function generateImgAttrs({
return { src, srcSet: undefined, sizes: undefined }
}
const { widths, kind } = getWidths(config, width, layout, sizes)
const { widths, kind } = getWidths(config, width, sizes)
const last = widths.length - 1
return {
......@@ -388,26 +231,13 @@ function generateImgAttrs({
}
function getInt(x: unknown): number | undefined {
if (typeof x === 'number') {
if (typeof x === 'number' || typeof x === 'undefined') {
return x
}
if (typeof x === 'string') {
if (typeof x === 'string' && /^[0-9]+$/.test(x)) {
return parseInt(x, 10)
}
return undefined
}
function defaultImageLoader(loaderProps: ImageLoaderPropsWithConfig) {
const loaderKey = loaderProps.config?.loader || 'default'
const load = loaders.get(loaderKey)
if (load) {
return load(loaderProps)
}
throw new Error(
`Unknown "loader" found in "next.config.js". Expected: ${VALID_LOADERS.join(
', '
)}. Received: ${loaderKey}`
)
return NaN
}
// See https://stackoverflow.com/q/39777833/266535 for why we use this ref
......@@ -415,12 +245,12 @@ function defaultImageLoader(loaderProps: ImageLoaderPropsWithConfig) {
function handleLoading(
img: ImgElementWithDataProp,
src: string,
layout: LayoutValue,
placeholder: PlaceholderValue,
onLoadRef: React.MutableRefObject<OnLoad | undefined>,
onLoadingCompleteRef: React.MutableRefObject<OnLoadingComplete | undefined>,
setBlurComplete: (b: boolean) => void
) {
if (!img || img.src === emptyDataURL || img['data-loaded-src'] === src) {
if (!img || img['data-loaded-src'] === src) {
return
}
img['data-loaded-src'] = src
......@@ -434,36 +264,79 @@ function handleLoading(
// - decode() completes
return
}
loadedImageURLs.add(src)
if (placeholder === 'blur') {
setBlurComplete(true)
}
if (onLoadRef?.current) {
const event = new Event('load')
Object.defineProperty(event, 'target', { writable: false, value: img })
let prevented = false
let stopped = false
const sytheticEvent = {
...event,
nativeEvent: event,
currentTarget: img,
target: img,
isDefaultPrevented: () => prevented,
isPropagationStopped: () => stopped,
persist: () => {},
preventDefault: () => {
prevented = true
event.preventDefault()
},
stopPropagation: () => {
stopped = true
event.stopPropagation()
},
}
onLoadRef.current(sytheticEvent)
}
if (onLoadingCompleteRef?.current) {
const { naturalWidth, naturalHeight } = img
// Pass back read-only primitive values but not the
// underlying DOM element because it could be misused.
onLoadingCompleteRef.current({ naturalWidth, naturalHeight })
onLoadingCompleteRef.current(img)
}
if (process.env.NODE_ENV !== 'production') {
if (img.parentElement?.parentElement) {
const parent = getComputedStyle(img.parentElement.parentElement)
if (!parent.position) {
// The parent has not been rendered to the dom yet and therefore it has no position. Skip the warnings for such cases.
} else if (layout === 'responsive' && parent.display === 'flex') {
if (img.getAttribute('data-nimg') === 'future-fill') {
if (
!img.getAttribute('sizes') ||
img.getAttribute('sizes') === '100vw'
) {
let widthViewportRatio =
img.getBoundingClientRect().width / window.innerWidth
if (widthViewportRatio < 0.6) {
warnOnce(
`Image with src "${src}" may not render properly as a child of a flex container. Consider wrapping the image with a div to configure the width.`
`Image with src "${src}" has "fill" but is missing "sizes" prop. Please add it to improve page performance. Read more: https://nextjs.org/docs/api-reference/next/future/image#sizes`
)
} else if (
layout === 'fill' &&
parent.position !== 'relative' &&
parent.position !== 'fixed' &&
parent.position !== 'absolute'
) {
}
}
if (img.parentElement) {
const { position } = window.getComputedStyle(img.parentElement)
const valid = ['absolute', 'fixed', 'relative']
if (!valid.includes(position)) {
warnOnce(
`Image with src "${src}" may not render properly with a parent using position:"${parent.position}". Consider changing the parent style to position:"relative" with a width and height.`
`Image with src "${src}" has "fill" and parent element with invalid "position". Provided "${position}" should be one of ${valid
.map(String)
.join(',')}.`
)
}
}
if (img.height === 0) {
warnOnce(
`Image with src "${src}" 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.`
)
}
}
const heightModified =
img.height.toString() !== img.getAttribute('height')
const widthModified = img.width.toString() !== img.getAttribute('width')
if (
(heightModified && !widthModified) ||
(!heightModified && widthModified)
) {
warnOnce(
`Image with src "${src}" has either width or height modified, but not the other. If you use CSS to change the size of your image, also include the styles 'width: "auto"' or 'height: "auto"' to maintain the aspect ratio.`
)
}
}
})
}
......@@ -473,24 +346,23 @@ const ImageElement = ({
heightInt,
widthInt,
qualityInt,
layout,
className,
imgStyle,
blurStyle,
isLazy,
fill,
placeholder,
loading,
srcString,
config,
unoptimized,
loader,
onLoadRef,
onLoadingCompleteRef,
setBlurComplete,
setIntersection,
setShowAltText,
onLoad,
onError,
isVisible,
noscriptSizes,
...rest
}: ImageElementProps) => {
loading = isLazy ? 'lazy' : loading
......@@ -499,36 +371,72 @@ const ImageElement = ({
<img
{...rest}
{...imgAttributes}
width={widthInt}
height={heightInt}
decoding="async"
data-nimg={layout}
data-nimg={`future${fill ? '-fill' : ''}`}
className={className}
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading={loading}
style={{ ...imgStyle, ...blurStyle }}
ref={useCallback(
(img: ImgElementWithDataProp) => {
(img: ImgElementWithDataProp | null) => {
if (!img) {
return
}
if (onError) {
// If the image has an error before react hydrates, then the error is lost.
// The workaround is to wait until the image is mounted which is after hydration,
// then we set the src again to trigger the error handler (if there was an error).
// eslint-disable-next-line no-self-assign
img.src = img.src
}
if (process.env.NODE_ENV !== 'production') {
if (img && !srcString) {
if (!srcString) {
console.error(`Image is missing required "src" property:`, img)
}
if (
img.getAttribute('objectFit') ||
img.getAttribute('objectfit')
) {
console.error(
`Image has unknown prop "objectFit". Did you mean to use the "style" prop instead?`,
img
)
}
if (
img.getAttribute('objectPosition') ||
img.getAttribute('objectposition')
) {
console.error(
`Image has unknown prop "objectPosition". Did you mean to use the "style" prop instead?`,
img
)
}
if (img.getAttribute('alt') === null) {
console.error(
`Image is missing required "alt" property. Please add Alternative Text to describe the image for screen readers and search engines.`
)
}
}
setIntersection(img)
if (img?.complete) {
if (img.complete) {
handleLoading(
img,
srcString,
layout,
placeholder,
onLoadRef,
onLoadingCompleteRef,
setBlurComplete
)
}
},
[
setIntersection,
srcString,
layout,
placeholder,
onLoadRef,
onLoadingCompleteRef,
setBlurComplete,
onError,
]
)}
onLoad={(event) => {
......@@ -536,16 +444,15 @@ const ImageElement = ({
handleLoading(
img,
srcString,
layout,
placeholder,
onLoadRef,
onLoadingCompleteRef,
setBlurComplete
)
if (onLoad) {
onLoad(event)
}
}}
onError={(event) => {
// if the real image fails to load, this will ensure "alt" is visible
setShowAltText(true)
if (placeholder === 'blur') {
// If the real image fails to load, this will still remove the placeholder.
setBlurComplete(true)
......@@ -555,48 +462,87 @@ const ImageElement = ({
}
}}
/>
{(isLazy || placeholder === 'blur') && (
<noscript>
<img
{...rest}
{...generateImgAttrs({
config,
src: srcString,
unoptimized,
layout,
width: widthInt,
quality: qualityInt,
sizes: noscriptSizes,
loader,
})}
decoding="async"
data-nimg={layout}
style={imgStyle}
className={className}
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading={loading}
/>
</noscript>
)}
</>
)
}
function defaultLoader({
config,
src,
width,
quality,
}: ImageLoaderPropsWithConfig): string {
if (process.env.NODE_ENV !== 'production') {
const missingValues = []
// these should always be provided but make sure they are
if (!src) missingValues.push('src')
if (!width) missingValues.push('width')
if (missingValues.length > 0) {
throw new Error(
`Next Image Optimization requires ${missingValues.join(
', '
)} to be provided. Make sure you pass them as props to the \`next/image\` component. Received: ${JSON.stringify(
{ src, width, quality }
)}`
)
}
if (src.startsWith('//')) {
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)`
)
}
if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
let parsedSrc: URL
try {
parsedSrc = new URL(src)
} catch (err) {
console.error(err)
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://)`
)
}
if (process.env.NODE_ENV !== 'test') {
// We use dynamic require because this should only error in development
const { hasMatch } = require('../shared/lib/match-remote-pattern')
if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
)
}
}
}
}
if (src.endsWith('.svg') && !config.dangerouslyAllowSVG) {
// Special case to make svg serve as-is to avoid proxying
// through the built-in Image Optimization API.
return src
}
return `${config.path}?url=${encodeURIComponent(src)}&w=${width}&q=${
quality || 75
}`
}
export default function Image({
src,
sizes,
unoptimized = false,
priority = false,
loading,
lazyRoot = null,
lazyBoundary,
className,
quality,
width,
height,
fill,
style,
objectFit,
objectPosition,
onLoad,
onLoadingComplete,
placeholder = 'empty',
blurDataURL,
......@@ -611,16 +557,8 @@ export default function Image({
}, [configContext])
let rest: Partial<ImageProps> = all
let layout: NonNullable<LayoutValue> = sizes ? 'responsive' : 'intrinsic'
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 on <img>:
delete rest.layout
}
let loader: ImageLoaderWithConfig = defaultImageLoader
let loader: ImageLoaderWithConfig = defaultLoader
if ('loader' in rest) {
if (rest.loader) {
const customImageLoader = rest.loader
......@@ -636,6 +574,10 @@ export default function Image({
}
let staticSrc = ''
let widthInt = getInt(width)
let heightInt = getInt(height)
let blurWidth: number | undefined
let blurHeight: number | undefined
if (isStaticImport(src)) {
const staticImageData = isStaticRequire(src) ? src.default : src
......@@ -646,11 +588,6 @@ export default function Image({
)}`
)
}
blurDataURL = blurDataURL || staticImageData.blurDataURL
staticSrc = staticImageData.src
if (!layout || layout !== 'fill') {
height = height || staticImageData.height
width = width || staticImageData.width
if (!staticImageData.height || !staticImageData.width) {
throw new Error(
`An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received ${JSON.stringify(
......@@ -658,6 +595,23 @@ export default function Image({
)}`
)
}
blurWidth = staticImageData.blurWidth
blurHeight = staticImageData.blurHeight
blurDataURL = blurDataURL || staticImageData.blurDataURL
staticSrc = staticImageData.src
if (!fill) {
if (!widthInt && !heightInt) {
widthInt = staticImageData.width
heightInt = staticImageData.height
} else if (widthInt && !heightInt) {
const ratio = widthInt / staticImageData.width
heightInt = Math.round(staticImageData.height * ratio)
} else if (!widthInt && heightInt) {
const ratio = heightInt / staticImageData.height
widthInt = Math.round(staticImageData.width * ratio)
}
}
}
src = typeof src === 'string' ? src : staticSrc
......@@ -669,73 +623,13 @@ export default function Image({
unoptimized = true
isLazy = false
}
if (typeof window !== 'undefined' && loadedImageURLs.has(src)) {
isLazy = false
}
if (config.unoptimized) {
unoptimized = true
}
const [blurComplete, setBlurComplete] = useState(false)
const [setIntersection, isIntersected, resetIntersected] =
useIntersection<HTMLImageElement>({
rootRef: lazyRoot,
rootMargin: lazyBoundary || '200px',
disabled: !isLazy,
})
const isVisible = !isLazy || isIntersected
const wrapperStyle: JSX.IntrinsicElements['span']['style'] = {
boxSizing: 'border-box',
display: 'block',
overflow: 'hidden',
width: 'initial',
height: 'initial',
background: 'none',
opacity: 1,
border: 0,
margin: 0,
padding: 0,
}
const sizerStyle: JSX.IntrinsicElements['span']['style'] = {
boxSizing: 'border-box',
display: 'block',
width: 'initial',
height: 'initial',
background: 'none',
opacity: 1,
border: 0,
margin: 0,
padding: 0,
}
let hasSizer = false
let sizerSvgUrl: string | undefined
const layoutStyle: ImgElementStyle = {
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
right: 0,
const [showAltText, setShowAltText] = useState(false)
boxSizing: 'border-box',
padding: 0,
border: 'none',
margin: 'auto',
display: 'block',
width: 0,
height: 0,
minWidth: '100%',
maxWidth: '100%',
minHeight: '100%',
maxHeight: '100%',
objectFit,
objectPosition,
}
let widthInt = getInt(width)
let heightInt = getInt(height)
const qualityInt = getInt(quality)
if (process.env.NODE_ENV !== 'production') {
......@@ -743,36 +637,55 @@ export default function Image({
// React doesn't show the stack trace and there's
// no `src` to help identify which image, so we
// instead console.error(ref) during mount.
widthInt = widthInt || 1
heightInt = heightInt || 1
unoptimized = true
} else {
if (!VALID_LAYOUT_VALUES.includes(layout)) {
if ((layout as any) === 'raw') {
if (fill) {
if (width) {
throw new Error(
`The layout="raw" experiment has been moved to a new module. Please import \`next/future/image\` instead.`
`Image with src "${src}" has both "width" and "fill" properties. Only one should be used.`
)
}
if (height) {
throw new Error(
`Image with src "${src}" has invalid "layout" property. Provided "${layout}" should be one of ${VALID_LAYOUT_VALUES.map(
String
).join(',')}.`
`Image with src "${src}" has both "height" and "fill" properties. Only one should be used.`
)
}
if (
(typeof widthInt !== 'undefined' && isNaN(widthInt)) ||
(typeof heightInt !== 'undefined' && isNaN(heightInt))
) {
if (style?.position && style.position !== 'absolute') {
throw new Error(
`Image with src "${src}" has invalid "width" or "height" property. These should be numeric values.`
`Image with src "${src}" has both "fill" and "style.position" properties. Images with "fill" always use position absolute - it cannot be modified.`
)
}
if (layout === 'fill' && (width || height)) {
warnOnce(
`Image with src "${src}" and "layout='fill'" has unused properties assigned. Please remove "width" and "height".`
if (style?.width && style.width !== '100%') {
throw new Error(
`Image with src "${src}" has both "fill" and "style.width" properties. Images with "fill" always use width 100% - it cannot be modified.`
)
}
if (style?.height && style.height !== '100%') {
throw new Error(
`Image with src "${src}" has both "fill" and "style.height" properties. Images with "fill" always use height 100% - it cannot be modified.`
)
}
} else {
if (typeof widthInt === 'undefined') {
throw new Error(
`Image with src "${src}" is missing required "width" property.`
)
} else if (isNaN(widthInt)) {
throw new Error(
`Image with src "${src}" has invalid "width" property. Expected a numeric value in pixels but received "${width}".`
)
}
if (typeof heightInt === 'undefined') {
throw new Error(
`Image with src "${src}" is missing required "height" property.`
)
} else if (isNaN(heightInt)) {
throw new Error(
`Image with src "${src}" has invalid "height" property. Expected a numeric value in pixels but received "${height}".`
)
}
}
}
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(
......@@ -785,17 +698,14 @@ export default function Image({
`Image with src "${src}" has both "priority" and "loading='lazy'" properties. Only one should be used.`
)
}
if (sizes && layout !== 'fill' && layout !== 'responsive') {
warnOnce(
`Image with src "${src}" has "sizes" property but it will be ignored. Only use "sizes" with "layout='fill'" or "layout='responsive'"`
)
}
if (placeholder === 'blur') {
if (layout !== 'fill' && (widthInt || 0) * (heightInt || 0) < 1600) {
if (widthInt && heightInt && widthInt * heightInt < 1600) {
warnOnce(
`Image with src "${src}" is smaller than 40x40. Consider removing the "placeholder='blur'" property to improve performance.`
)
}
if (!blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader
......@@ -817,7 +727,7 @@ export default function Image({
)
}
if (!unoptimized && loader !== defaultImageLoader) {
if (!unoptimized && loader !== defaultLoader) {
const urlStr = loader({
config,
src,
......@@ -836,19 +746,6 @@ export default function Image({
}
}
if (style) {
let overwrittenStyles = Object.keys(style).filter(
(key) => key in layoutStyle
)
if (overwrittenStyles.length) {
warnOnce(
`Image with src ${src} is assigned the following styles, which are overwritten by automatically-generated styles: ${overwrittenStyles.join(
', '
)}`
)
}
}
if (
typeof window !== 'undefined' &&
!perfObserver &&
......@@ -885,80 +782,58 @@ export default function Image({
}
}
}
}
const imgStyle = Object.assign({}, style, layoutStyle)
const blurStyle =
placeholder === 'blur' && !blurComplete
const imgStyle = Object.assign(
fill
? {
backgroundSize: objectFit || 'cover',
backgroundPosition: objectPosition || '0% 0%',
filter: 'blur(20px)',
backgroundImage: `url("${blurDataURL}")`,
}
: {}
if (layout === 'fill') {
// <Image src="i.png" layout="fill" />
wrapperStyle.display = 'block'
wrapperStyle.position = 'absolute'
wrapperStyle.top = 0
wrapperStyle.left = 0
wrapperStyle.bottom = 0
wrapperStyle.right = 0
} else if (
typeof widthInt !== 'undefined' &&
typeof heightInt !== 'undefined'
) {
// <Image src="i.png" width="100" height="100" />
const quotient = heightInt / widthInt
const paddingTop = isNaN(quotient) ? '100%' : `${quotient * 100}%`
if (layout === 'responsive') {
// <Image src="i.png" width="100" height="100" layout="responsive" />
wrapperStyle.display = 'block'
wrapperStyle.position = 'relative'
hasSizer = true
sizerStyle.paddingTop = paddingTop
} else if (layout === 'intrinsic') {
// <Image src="i.png" width="100" height="100" layout="intrinsic" />
wrapperStyle.display = 'inline-block'
wrapperStyle.position = 'relative'
wrapperStyle.maxWidth = '100%'
hasSizer = true
sizerStyle.maxWidth = '100%'
sizerSvgUrl = `data:image/svg+xml,%3csvg%20xmlns=%27http://www.w3.org/2000/svg%27%20version=%271.1%27%20width=%27${widthInt}%27%20height=%27${heightInt}%27/%3e`
} else if (layout === 'fixed') {
// <Image src="i.png" width="100" height="100" layout="fixed" />
wrapperStyle.display = 'inline-block'
wrapperStyle.position = 'relative'
wrapperStyle.width = widthInt
wrapperStyle.height = heightInt
position: 'absolute',
height: '100%',
width: '100%',
left: 0,
top: 0,
right: 0,
bottom: 0,
}
} else {
// <Image src="i.png" />
if (process.env.NODE_ENV !== 'production') {
throw new Error(
`Image with src "${src}" must use "width" and "height" properties or "layout='fill'" property.`
: {},
showAltText ? {} : { color: 'transparent' },
style
)
const blurStyle =
placeholder === 'blur' && blurDataURL && !blurComplete
? {
backgroundSize: imgStyle.objectFit || 'cover',
backgroundPosition: imgStyle.objectPosition || '50% 50%',
backgroundRepeat: 'no-repeat',
backgroundImage: `url("data:image/svg+xml;charset=utf-8,${getImageBlurSvg(
{
widthInt,
heightInt,
blurWidth,
blurHeight,
blurDataURL,
}
)}")`,
}
: {}
let imgAttributes: GenImgAttrsResult = {
src: emptyDataURL,
srcSet: undefined,
sizes: undefined,
if (process.env.NODE_ENV === 'development') {
if (blurStyle.backgroundImage && blurDataURL?.startsWith('/')) {
// During `next dev`, we don't want to generate blur placeholders with webpack
// because it can delay starting the dev server. Instead, `next-image-loader.js`
// will inline a special url to lazily generate the blur placeholder at request time.
blurStyle.backgroundImage = `url("${blurDataURL}")`
}
}
if (isVisible) {
imgAttributes = generateImgAttrs({
const imgAttributes = generateImgAttrs({
config,
src,
unoptimized,
layout,
width: widthInt,
quality: qualityInt,
sizes,
loader,
})
}
let srcString: string = src
......@@ -990,74 +865,43 @@ export default function Image({
crossOrigin: rest.crossOrigin,
}
const useLayoutEffect =
typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect
const onLoadRef = useRef(onLoad)
useEffect(() => {
onLoadRef.current = onLoad
}, [onLoad])
const onLoadingCompleteRef = useRef(onLoadingComplete)
const previousImageSrc = useRef<string | StaticImport>(src)
useEffect(() => {
onLoadingCompleteRef.current = onLoadingComplete
}, [onLoadingComplete])
useLayoutEffect(() => {
if (previousImageSrc.current !== src) {
resetIntersected()
previousImageSrc.current = src
}
}, [resetIntersected, src])
const imgElementArgs = {
const imgElementArgs: ImageElementProps = {
isLazy,
imgAttributes,
heightInt,
widthInt,
qualityInt,
layout,
className,
imgStyle,
blurStyle,
loading,
config,
fill,
unoptimized,
placeholder,
loader,
srcString,
onLoadRef,
onLoadingCompleteRef,
setBlurComplete,
setIntersection,
isVisible,
noscriptSizes: sizes,
setShowAltText,
...rest,
}
return (
<>
{
<span style={wrapperStyle}>
{hasSizer ? (
<span style={sizerStyle}>
{sizerSvgUrl ? (
<img
style={{
display: 'block',
maxWidth: '100%',
width: 'initial',
height: 'initial',
background: 'none',
opacity: 1,
border: 0,
margin: 0,
padding: 0,
}}
alt=""
aria-hidden={true}
src={sizerSvgUrl}
/>
) : null}
</span>
) : null}
<ImageElement {...imgElementArgs} />
</span>
}
{<ImageElement {...imgElementArgs} />}
{priority ? (
// Note how we omit the `href` attribute, as it would only be relevant
// for browsers that do not support `imagesrcset`, and in those cases
......
......@@ -9,20 +9,30 @@ import React, {
useState,
} from 'react'
import Head from '../../shared/lib/head'
import { getImageBlurSvg } from '../../shared/lib/image-blur-svg'
import {
ImageConfigComplete,
imageConfigDefault,
LoaderValue,
VALID_LOADERS,
} from '../../shared/lib/image-config'
import { useIntersection } from '../use-intersection'
import { ImageConfigContext } from '../../shared/lib/image-config-context'
import { warnOnce } from '../../shared/lib/utils'
import { normalizePathTrailingSlash } from '../normalize-trailing-slash'
function normalizeSrc(src: string): string {
return src[0] === '/' ? src.slice(1) : src
}
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete
const loadedImageURLs = new Set<string>()
const allImgs = new Map<
string,
{ src: string; priority: boolean; placeholder: string }
>()
let perfObserver: PerformanceObserver | undefined
const emptyDataURL =
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
if (typeof window === 'undefined') {
;(global as any).__NEXT_IMAGE_IMPORTED = true
......@@ -31,7 +41,7 @@ if (typeof window === 'undefined') {
const VALID_LOADING_VALUES = ['lazy', 'eager', undefined] as const
type LoadingValue = typeof VALID_LOADING_VALUES[number]
type ImageConfig = ImageConfigComplete & { allSizes: number[] }
export type ImageLoader = (p: ImageLoaderProps) => string
export type ImageLoader = (resolverProps: ImageLoaderProps) => string
export type ImageLoaderProps = {
src: string
......@@ -42,14 +52,152 @@ export type ImageLoaderProps = {
// Do not export - this is an internal type only
// because `next.config.js` is only meant for the
// built-in loaders, not for a custom loader() prop.
type ImageLoaderWithConfig = (p: ImageLoaderPropsWithConfig) => string
type ImageLoaderWithConfig = (
resolverProps: ImageLoaderPropsWithConfig
) => string
type ImageLoaderPropsWithConfig = ImageLoaderProps & {
config: Readonly<ImageConfig>
}
function imgixLoader({
config,
src,
width,
quality,
}: ImageLoaderPropsWithConfig): string {
// Demo: https://static.imgix.net/daisy.png?auto=format&fit=max&w=300
const url = new URL(`${config.path}${normalizeSrc(src)}`)
const params = url.searchParams
// auto params can be combined with comma separation, or reiteration
params.set('auto', params.getAll('auto').join(',') || 'format')
params.set('fit', params.get('fit') || 'max')
params.set('w', params.get('w') || width.toString())
if (quality) {
params.set('q', quality.toString())
}
return url.href
}
function akamaiLoader({
config,
src,
width,
}: ImageLoaderPropsWithConfig): string {
return `${config.path}${normalizeSrc(src)}?imwidth=${width}`
}
function cloudinaryLoader({
config,
src,
width,
quality,
}: ImageLoaderPropsWithConfig): string {
// Demo: https://res.cloudinary.com/demo/image/upload/w_300,c_limit,q_auto/turtles.jpg
const params = ['f_auto', 'c_limit', 'w_' + width, 'q_' + (quality || 'auto')]
const paramsString = params.join(',') + '/'
return `${config.path}${paramsString}${normalizeSrc(src)}`
}
function customLoader({ src }: ImageLoaderProps): string {
throw new Error(
`Image with src "${src}" is missing "loader" prop.` +
`\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader`
)
}
function defaultLoader({
config,
src,
width,
quality,
}: ImageLoaderPropsWithConfig): string {
if (process.env.NODE_ENV !== 'production') {
const missingValues = []
// these should always be provided but make sure they are
if (!src) missingValues.push('src')
if (!width) missingValues.push('width')
if (missingValues.length > 0) {
throw new Error(
`Next Image Optimization requires ${missingValues.join(
', '
)} to be provided. Make sure you pass them as props to the \`next/image\` component. Received: ${JSON.stringify(
{ src, width, quality }
)}`
)
}
if (src.startsWith('//')) {
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)`
)
}
if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
let parsedSrc: URL
try {
parsedSrc = new URL(src)
} catch (err) {
console.error(err)
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://)`
)
}
if (process.env.NODE_ENV !== 'test') {
// We use dynamic require because this should only error in development
const { hasMatch } = require('../../shared/lib/match-remote-pattern')
if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
)
}
}
}
}
if (src.endsWith('.svg') && !config.dangerouslyAllowSVG) {
// Special case to make svg serve as-is to avoid proxying
// through the built-in Image Optimization API.
return src
}
return `${normalizePathTrailingSlash(config.path)}?url=${encodeURIComponent(
src
)}&w=${width}&q=${quality || 75}`
}
const loaders = new Map<
LoaderValue,
(props: ImageLoaderPropsWithConfig) => string
>([
['default', defaultLoader],
['imgix', imgixLoader],
['cloudinary', cloudinaryLoader],
['akamai', akamaiLoader],
['custom', customLoader],
])
const VALID_LAYOUT_VALUES = [
'fill',
'fixed',
'intrinsic',
'responsive',
undefined,
] as const
type LayoutValue = typeof VALID_LAYOUT_VALUES[number]
type PlaceholderValue = 'blur' | 'empty'
type OnLoad = React.ReactEventHandler<HTMLImageElement> | undefined
type OnLoadingComplete = (img: HTMLImageElement) => void
type OnLoadingComplete = (result: {
naturalWidth: number
naturalHeight: number
}) => void
type ImgElementStyle = NonNullable<JSX.IntrinsicElements['img']['style']>
......@@ -62,8 +210,6 @@ export interface StaticImageData {
height: number
width: number
blurDataURL?: string
blurWidth?: number
blurHeight?: number
}
interface StaticRequire {
......@@ -96,50 +242,55 @@ function isStaticImport(src: string | StaticImport): src is StaticImport {
export type ImageProps = Omit<
JSX.IntrinsicElements['img'],
'src' | 'srcSet' | 'ref' | 'alt' | 'width' | 'height' | 'loading'
'src' | 'srcSet' | 'ref' | 'width' | 'height' | 'loading'
> & {
src: string | StaticImport
alt: string
width?: SafeNumber
height?: SafeNumber
fill?: boolean
layout?: LayoutValue
loader?: ImageLoader
quality?: SafeNumber
priority?: boolean
loading?: LoadingValue
lazyRoot?: React.RefObject<HTMLElement> | null
lazyBoundary?: string
placeholder?: PlaceholderValue
blurDataURL?: string
unoptimized?: boolean
objectFit?: ImgElementStyle['objectFit']
objectPosition?: ImgElementStyle['objectPosition']
onLoadingComplete?: OnLoadingComplete
}
type ImageElementProps = Omit<ImageProps, 'src' | 'alt' | 'loader'> & {
type ImageElementProps = Omit<ImageProps, 'src' | 'loader'> & {
srcString: string
imgAttributes: GenImgAttrsResult
heightInt: number | undefined
widthInt: number | undefined
qualityInt: number | undefined
layout: LayoutValue
imgStyle: ImgElementStyle
blurStyle: ImgElementStyle
isLazy: boolean
fill?: boolean
loading: LoadingValue
config: ImageConfig
unoptimized: boolean
loader: ImageLoaderWithConfig
placeholder: PlaceholderValue
onLoadRef: React.MutableRefObject<OnLoad | undefined>
onLoadingCompleteRef: React.MutableRefObject<OnLoadingComplete | undefined>
setBlurComplete: (b: boolean) => void
setShowAltText: (b: boolean) => void
setIntersection: (img: HTMLImageElement | null) => void
isVisible: boolean
noscriptSizes: string | undefined
}
function getWidths(
{ deviceSizes, allSizes }: ImageConfig,
width: number | undefined,
layout: LayoutValue,
sizes: string | undefined
): { widths: number[]; kind: 'w' | 'x' } {
if (sizes) {
if (sizes && (layout === 'fill' || layout === 'responsive')) {
// Find all the "vw" percent sizes used in the sizes prop
const viewportWidthRe = /(^|\s)(1?\d?\d)vw/g
const percentSizes = []
......@@ -155,7 +306,11 @@ function getWidths(
}
return { widths: allSizes, kind: 'w' }
}
if (typeof width !== 'number') {
if (
typeof width !== 'number' ||
layout === 'fill' ||
layout === 'responsive'
) {
return { widths: deviceSizes, kind: 'w' }
}
......@@ -181,6 +336,7 @@ type GenImgAttrsData = {
config: ImageConfig
src: string
unoptimized: boolean
layout: LayoutValue
loader: ImageLoaderWithConfig
width?: number
quality?: number
......@@ -197,6 +353,7 @@ function generateImgAttrs({
config,
src,
unoptimized,
layout,
width,
quality,
sizes,
......@@ -206,7 +363,7 @@ function generateImgAttrs({
return { src, srcSet: undefined, sizes: undefined }
}
const { widths, kind } = getWidths(config, width, sizes)
const { widths, kind } = getWidths(config, width, layout, sizes)
const last = widths.length - 1
return {
......@@ -231,13 +388,26 @@ function generateImgAttrs({
}
function getInt(x: unknown): number | undefined {
if (typeof x === 'number' || typeof x === 'undefined') {
if (typeof x === 'number') {
return x
}
if (typeof x === 'string' && /^[0-9]+$/.test(x)) {
if (typeof x === 'string') {
return parseInt(x, 10)
}
return NaN
return undefined
}
function defaultImageLoader(loaderProps: ImageLoaderPropsWithConfig) {
const loaderKey = loaderProps.config?.loader || 'default'
const load = loaders.get(loaderKey)
if (load) {
return load(loaderProps)
}
throw new Error(
`Unknown "loader" found in "next.config.js". Expected: ${VALID_LOADERS.join(
', '
)}. Received: ${loaderKey}`
)
}
// See https://stackoverflow.com/q/39777833/266535 for why we use this ref
......@@ -245,12 +415,12 @@ function getInt(x: unknown): number | undefined {
function handleLoading(
img: ImgElementWithDataProp,
src: string,
layout: LayoutValue,
placeholder: PlaceholderValue,
onLoadRef: React.MutableRefObject<OnLoad | undefined>,
onLoadingCompleteRef: React.MutableRefObject<OnLoadingComplete | undefined>,
setBlurComplete: (b: boolean) => void
) {
if (!img || img['data-loaded-src'] === src) {
if (!img || img.src === emptyDataURL || img['data-loaded-src'] === src) {
return
}
img['data-loaded-src'] = src
......@@ -264,80 +434,37 @@ function handleLoading(
// - decode() completes
return
}
loadedImageURLs.add(src)
if (placeholder === 'blur') {
setBlurComplete(true)
}
if (onLoadRef?.current) {
const event = new Event('load')
Object.defineProperty(event, 'target', { writable: false, value: img })
let prevented = false
let stopped = false
const sytheticEvent = {
...event,
nativeEvent: event,
currentTarget: img,
target: img,
isDefaultPrevented: () => prevented,
isPropagationStopped: () => stopped,
persist: () => {},
preventDefault: () => {
prevented = true
event.preventDefault()
},
stopPropagation: () => {
stopped = true
event.stopPropagation()
},
}
onLoadRef.current(sytheticEvent)
}
if (onLoadingCompleteRef?.current) {
onLoadingCompleteRef.current(img)
const { naturalWidth, naturalHeight } = img
// Pass back read-only primitive values but not the
// underlying DOM element because it could be misused.
onLoadingCompleteRef.current({ naturalWidth, naturalHeight })
}
if (process.env.NODE_ENV !== 'production') {
if (img.getAttribute('data-nimg') === 'future-fill') {
if (
!img.getAttribute('sizes') ||
img.getAttribute('sizes') === '100vw'
) {
let widthViewportRatio =
img.getBoundingClientRect().width / window.innerWidth
if (widthViewportRatio < 0.6) {
if (img.parentElement?.parentElement) {
const parent = getComputedStyle(img.parentElement.parentElement)
if (!parent.position) {
// The parent has not been rendered to the dom yet and therefore it has no position. Skip the warnings for such cases.
} else if (layout === 'responsive' && parent.display === 'flex') {
warnOnce(
`Image with src "${src}" has "fill" but is missing "sizes" prop. Please add it to improve page performance. Read more: https://nextjs.org/docs/api-reference/next/future/image#sizes`
`Image with src "${src}" may not render properly as a child of a flex container. Consider wrapping the image with a div to configure the width.`
)
}
}
if (img.parentElement) {
const { position } = window.getComputedStyle(img.parentElement)
const valid = ['absolute', 'fixed', 'relative']
if (!valid.includes(position)) {
warnOnce(
`Image with src "${src}" has "fill" and parent element with invalid "position". Provided "${position}" should be one of ${valid
.map(String)
.join(',')}.`
)
}
}
if (img.height === 0) {
warnOnce(
`Image with src "${src}" 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.`
)
}
}
const heightModified =
img.height.toString() !== img.getAttribute('height')
const widthModified = img.width.toString() !== img.getAttribute('width')
if (
(heightModified && !widthModified) ||
(!heightModified && widthModified)
} else if (
layout === 'fill' &&
parent.position !== 'relative' &&
parent.position !== 'fixed' &&
parent.position !== 'absolute'
) {
warnOnce(
`Image with src "${src}" has either width or height modified, but not the other. If you use CSS to change the size of your image, also include the styles 'width: "auto"' or 'height: "auto"' to maintain the aspect ratio.`
`Image with src "${src}" may not render properly with a parent using position:"${parent.position}". Consider changing the parent style to position:"relative" with a width and height.`
)
}
}
}
})
}
......@@ -346,23 +473,24 @@ const ImageElement = ({
heightInt,
widthInt,
qualityInt,
layout,
className,
imgStyle,
blurStyle,
isLazy,
fill,
placeholder,
loading,
srcString,
config,
unoptimized,
loader,
onLoadRef,
onLoadingCompleteRef,
setBlurComplete,
setShowAltText,
setIntersection,
onLoad,
onError,
isVisible,
noscriptSizes,
...rest
}: ImageElementProps) => {
loading = isLazy ? 'lazy' : loading
......@@ -371,72 +499,36 @@ const ImageElement = ({
<img
{...rest}
{...imgAttributes}
width={widthInt}
height={heightInt}
decoding="async"
data-nimg={`future${fill ? '-fill' : ''}`}
data-nimg={layout}
className={className}
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading={loading}
style={{ ...imgStyle, ...blurStyle }}
ref={useCallback(
(img: ImgElementWithDataProp | null) => {
if (!img) {
return
}
if (onError) {
// If the image has an error before react hydrates, then the error is lost.
// The workaround is to wait until the image is mounted which is after hydration,
// then we set the src again to trigger the error handler (if there was an error).
// eslint-disable-next-line no-self-assign
img.src = img.src
}
(img: ImgElementWithDataProp) => {
if (process.env.NODE_ENV !== 'production') {
if (!srcString) {
if (img && !srcString) {
console.error(`Image is missing required "src" property:`, img)
}
if (
img.getAttribute('objectFit') ||
img.getAttribute('objectfit')
) {
console.error(
`Image has unknown prop "objectFit". Did you mean to use the "style" prop instead?`,
img
)
}
if (
img.getAttribute('objectPosition') ||
img.getAttribute('objectposition')
) {
console.error(
`Image has unknown prop "objectPosition". Did you mean to use the "style" prop instead?`,
img
)
}
if (img.getAttribute('alt') === null) {
console.error(
`Image is missing required "alt" property. Please add Alternative Text to describe the image for screen readers and search engines.`
)
}
}
if (img.complete) {
setIntersection(img)
if (img?.complete) {
handleLoading(
img,
srcString,
layout,
placeholder,
onLoadRef,
onLoadingCompleteRef,
setBlurComplete
)
}
},
[
setIntersection,
srcString,
layout,
placeholder,
onLoadRef,
onLoadingCompleteRef,
setBlurComplete,
onError,
]
)}
onLoad={(event) => {
......@@ -444,15 +536,16 @@ const ImageElement = ({
handleLoading(
img,
srcString,
layout,
placeholder,
onLoadRef,
onLoadingCompleteRef,
setBlurComplete
)
if (onLoad) {
onLoad(event)
}
}}
onError={(event) => {
// if the real image fails to load, this will ensure "alt" is visible
setShowAltText(true)
if (placeholder === 'blur') {
// If the real image fails to load, this will still remove the placeholder.
setBlurComplete(true)
......@@ -462,72 +555,31 @@ const ImageElement = ({
}
}}
/>
</>
)
}
function defaultLoader({
{(isLazy || placeholder === 'blur') && (
<noscript>
<img
{...rest}
{...generateImgAttrs({
config,
src,
width,
quality,
}: ImageLoaderPropsWithConfig): string {
if (process.env.NODE_ENV !== 'production') {
const missingValues = []
// these should always be provided but make sure they are
if (!src) missingValues.push('src')
if (!width) missingValues.push('width')
if (missingValues.length > 0) {
throw new Error(
`Next Image Optimization requires ${missingValues.join(
', '
)} to be provided. Make sure you pass them as props to the \`next/image\` component. Received: ${JSON.stringify(
{ src, width, quality }
)}`
)
}
if (src.startsWith('//')) {
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)`
)
}
if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
let parsedSrc: URL
try {
parsedSrc = new URL(src)
} catch (err) {
console.error(err)
throw new Error(
`Failed to parse src "${src}" on \`next/image\`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://)`
)
}
if (process.env.NODE_ENV !== 'test') {
// We use dynamic require because this should only error in development
const { hasMatch } = require('../../shared/lib/match-remote-pattern')
if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
src: srcString,
unoptimized,
layout,
width: widthInt,
quality: qualityInt,
sizes: noscriptSizes,
loader,
})}
decoding="async"
data-nimg={layout}
style={imgStyle}
className={className}
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading={loading}
/>
</noscript>
)}
</>
)
}
}
}
}
if (src.endsWith('.svg') && !config.dangerouslyAllowSVG) {
// Special case to make svg serve as-is to avoid proxying
// through the built-in Image Optimization API.
return src
}
return `${config.path}?url=${encodeURIComponent(src)}&w=${width}&q=${
quality || 75
}`
}
export default function Image({
......@@ -536,13 +588,15 @@ export default function Image({
unoptimized = false,
priority = false,
loading,
lazyRoot = null,
lazyBoundary,
className,
quality,
width,
height,
fill,
style,
onLoad,
objectFit,
objectPosition,
onLoadingComplete,
placeholder = 'empty',
blurDataURL,
......@@ -557,8 +611,16 @@ export default function Image({
}, [configContext])
let rest: Partial<ImageProps> = all
let layout: NonNullable<LayoutValue> = sizes ? 'responsive' : 'intrinsic'
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 on <img>:
delete rest.layout
}
let loader: ImageLoaderWithConfig = defaultLoader
let loader: ImageLoaderWithConfig = defaultImageLoader
if ('loader' in rest) {
if (rest.loader) {
const customImageLoader = rest.loader
......@@ -574,10 +636,6 @@ export default function Image({
}
let staticSrc = ''
let widthInt = getInt(width)
let heightInt = getInt(height)
let blurWidth: number | undefined
let blurHeight: number | undefined
if (isStaticImport(src)) {
const staticImageData = isStaticRequire(src) ? src.default : src
......@@ -588,6 +646,11 @@ export default function Image({
)}`
)
}
blurDataURL = blurDataURL || staticImageData.blurDataURL
staticSrc = staticImageData.src
if (!layout || layout !== 'fill') {
height = height || staticImageData.height
width = width || staticImageData.width
if (!staticImageData.height || !staticImageData.width) {
throw new Error(
`An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received ${JSON.stringify(
......@@ -595,23 +658,6 @@ export default function Image({
)}`
)
}
blurWidth = staticImageData.blurWidth
blurHeight = staticImageData.blurHeight
blurDataURL = blurDataURL || staticImageData.blurDataURL
staticSrc = staticImageData.src
if (!fill) {
if (!widthInt && !heightInt) {
widthInt = staticImageData.width
heightInt = staticImageData.height
} else if (widthInt && !heightInt) {
const ratio = widthInt / staticImageData.width
heightInt = Math.round(staticImageData.height * ratio)
} else if (!widthInt && heightInt) {
const ratio = heightInt / staticImageData.height
widthInt = Math.round(staticImageData.width * ratio)
}
}
}
src = typeof src === 'string' ? src : staticSrc
......@@ -623,13 +669,73 @@ export default function Image({
unoptimized = true
isLazy = false
}
if (typeof window !== 'undefined' && loadedImageURLs.has(src)) {
isLazy = false
}
if (config.unoptimized) {
unoptimized = true
}
const [blurComplete, setBlurComplete] = useState(false)
const [showAltText, setShowAltText] = useState(false)
const [setIntersection, isIntersected, resetIntersected] =
useIntersection<HTMLImageElement>({
rootRef: lazyRoot,
rootMargin: lazyBoundary || '200px',
disabled: !isLazy,
})
const isVisible = !isLazy || isIntersected
const wrapperStyle: JSX.IntrinsicElements['span']['style'] = {
boxSizing: 'border-box',
display: 'block',
overflow: 'hidden',
width: 'initial',
height: 'initial',
background: 'none',
opacity: 1,
border: 0,
margin: 0,
padding: 0,
}
const sizerStyle: JSX.IntrinsicElements['span']['style'] = {
boxSizing: 'border-box',
display: 'block',
width: 'initial',
height: 'initial',
background: 'none',
opacity: 1,
border: 0,
margin: 0,
padding: 0,
}
let hasSizer = false
let sizerSvgUrl: string | undefined
const layoutStyle: ImgElementStyle = {
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%',
objectFit,
objectPosition,
}
let widthInt = getInt(width)
let heightInt = getInt(height)
const qualityInt = getInt(quality)
if (process.env.NODE_ENV !== 'production') {
......@@ -637,55 +743,31 @@ export default function Image({
// React doesn't show the stack trace and there's
// no `src` to help identify which image, so we
// instead console.error(ref) during mount.
widthInt = widthInt || 1
heightInt = heightInt || 1
unoptimized = true
} else {
if (fill) {
if (width) {
throw new Error(
`Image with src "${src}" has both "width" and "fill" properties. Only one should be used.`
)
}
if (height) {
throw new Error(
`Image with src "${src}" has both "height" and "fill" properties. Only one should be used.`
)
}
if (style?.position && style.position !== 'absolute') {
if (!VALID_LAYOUT_VALUES.includes(layout)) {
throw new Error(
`Image with src "${src}" has both "fill" and "style.position" properties. Images with "fill" always use position absolute - it cannot be modified.`
)
}
if (style?.width && style.width !== '100%') {
throw new Error(
`Image with src "${src}" has both "fill" and "style.width" properties. Images with "fill" always use width 100% - it cannot be modified.`
)
}
if (style?.height && style.height !== '100%') {
throw new Error(
`Image with src "${src}" has both "fill" and "style.height" properties. Images with "fill" always use height 100% - it cannot be modified.`
`Image with src "${src}" has invalid "layout" property. Provided "${layout}" should be one of ${VALID_LAYOUT_VALUES.map(
String
).join(',')}.`
)
}
} else {
if (typeof widthInt === 'undefined') {
throw new Error(
`Image with src "${src}" is missing required "width" property.`
)
} else if (isNaN(widthInt)) {
if (
(typeof widthInt !== 'undefined' && isNaN(widthInt)) ||
(typeof heightInt !== 'undefined' && isNaN(heightInt))
) {
throw new Error(
`Image with src "${src}" has invalid "width" property. Expected a numeric value in pixels but received "${width}".`
`Image with src "${src}" has invalid "width" or "height" property. These should be numeric values.`
)
}
if (typeof heightInt === 'undefined') {
throw new Error(
`Image with src "${src}" is missing required "height" property.`
)
} else if (isNaN(heightInt)) {
throw new Error(
`Image with src "${src}" has invalid "height" property. Expected a numeric value in pixels but received "${height}".`
if (layout === 'fill' && (width || height)) {
warnOnce(
`Image with src "${src}" and "layout='fill'" has unused properties assigned. Please remove "width" and "height".`
)
}
}
}
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(
......@@ -698,14 +780,17 @@ export default function Image({
`Image with src "${src}" has both "priority" and "loading='lazy'" properties. Only one should be used.`
)
}
if (sizes && layout !== 'fill' && layout !== 'responsive') {
warnOnce(
`Image with src "${src}" has "sizes" property but it will be ignored. Only use "sizes" with "layout='fill'" or "layout='responsive'"`
)
}
if (placeholder === 'blur') {
if (widthInt && heightInt && widthInt * heightInt < 1600) {
if (layout !== 'fill' && (widthInt || 0) * (heightInt || 0) < 1600) {
warnOnce(
`Image with src "${src}" is smaller than 40x40. Consider removing the "placeholder='blur'" property to improve performance.`
)
}
if (!blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader
......@@ -727,7 +812,7 @@ export default function Image({
)
}
if (!unoptimized && loader !== defaultLoader) {
if (!unoptimized && loader !== defaultImageLoader) {
const urlStr = loader({
config,
src,
......@@ -746,6 +831,19 @@ export default function Image({
}
}
if (style) {
let overwrittenStyles = Object.keys(style).filter(
(key) => key in layoutStyle
)
if (overwrittenStyles.length) {
warnOnce(
`Image with src ${src} is assigned the following styles, which are overwritten by automatically-generated styles: ${overwrittenStyles.join(
', '
)}`
)
}
}
if (
typeof window !== 'undefined' &&
!perfObserver &&
......@@ -782,58 +880,80 @@ export default function Image({
}
}
}
const imgStyle = Object.assign(
fill
? {
position: 'absolute',
height: '100%',
width: '100%',
left: 0,
top: 0,
right: 0,
bottom: 0,
}
: {},
showAltText ? {} : { color: 'transparent' },
style
)
const imgStyle = Object.assign({}, style, layoutStyle)
const blurStyle =
placeholder === 'blur' && blurDataURL && !blurComplete
placeholder === 'blur' && !blurComplete
? {
backgroundSize: imgStyle.objectFit || 'cover',
backgroundPosition: imgStyle.objectPosition || '50% 50%',
backgroundRepeat: 'no-repeat',
backgroundImage: `url("data:image/svg+xml;charset=utf-8,${getImageBlurSvg(
{
widthInt,
heightInt,
blurWidth,
blurHeight,
blurDataURL,
}
)}")`,
backgroundSize: objectFit || 'cover',
backgroundPosition: objectPosition || '0% 0%',
filter: 'blur(20px)',
backgroundImage: `url("${blurDataURL}")`,
}
: {}
if (process.env.NODE_ENV === 'development') {
if (blurStyle.backgroundImage && blurDataURL?.startsWith('/')) {
// During `next dev`, we don't want to generate blur placeholders with webpack
// because it can delay starting the dev server. Instead, `next-image-loader.js`
// will inline a special url to lazily generate the blur placeholder at request time.
blurStyle.backgroundImage = `url("${blurDataURL}")`
if (layout === 'fill') {
// <Image src="i.png" layout="fill" />
wrapperStyle.display = 'block'
wrapperStyle.position = 'absolute'
wrapperStyle.top = 0
wrapperStyle.left = 0
wrapperStyle.bottom = 0
wrapperStyle.right = 0
} else if (
typeof widthInt !== 'undefined' &&
typeof heightInt !== 'undefined'
) {
// <Image src="i.png" width="100" height="100" />
const quotient = heightInt / widthInt
const paddingTop = isNaN(quotient) ? '100%' : `${quotient * 100}%`
if (layout === 'responsive') {
// <Image src="i.png" width="100" height="100" layout="responsive" />
wrapperStyle.display = 'block'
wrapperStyle.position = 'relative'
hasSizer = true
sizerStyle.paddingTop = paddingTop
} else if (layout === 'intrinsic') {
// <Image src="i.png" width="100" height="100" layout="intrinsic" />
wrapperStyle.display = 'inline-block'
wrapperStyle.position = 'relative'
wrapperStyle.maxWidth = '100%'
hasSizer = true
sizerStyle.maxWidth = '100%'
sizerSvgUrl = `data:image/svg+xml,%3csvg%20xmlns=%27http://www.w3.org/2000/svg%27%20version=%271.1%27%20width=%27${widthInt}%27%20height=%27${heightInt}%27/%3e`
} else if (layout === 'fixed') {
// <Image src="i.png" width="100" height="100" layout="fixed" />
wrapperStyle.display = 'inline-block'
wrapperStyle.position = 'relative'
wrapperStyle.width = widthInt
wrapperStyle.height = heightInt
}
} else {
// <Image src="i.png" />
if (process.env.NODE_ENV !== 'production') {
throw new Error(
`Image with src "${src}" must use "width" and "height" properties or "layout='fill'" property.`
)
}
}
let imgAttributes: GenImgAttrsResult = {
src: emptyDataURL,
srcSet: undefined,
sizes: undefined,
}
const imgAttributes = generateImgAttrs({
if (isVisible) {
imgAttributes = generateImgAttrs({
config,
src,
unoptimized,
layout,
width: widthInt,
quality: qualityInt,
sizes,
loader,
})
}
let srcString: string = src
......@@ -865,43 +985,74 @@ export default function Image({
crossOrigin: rest.crossOrigin,
}
const onLoadRef = useRef(onLoad)
useEffect(() => {
onLoadRef.current = onLoad
}, [onLoad])
const useLayoutEffect =
typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect
const onLoadingCompleteRef = useRef(onLoadingComplete)
const previousImageSrc = useRef<string | StaticImport>(src)
useEffect(() => {
onLoadingCompleteRef.current = onLoadingComplete
}, [onLoadingComplete])
const imgElementArgs: ImageElementProps = {
useLayoutEffect(() => {
if (previousImageSrc.current !== src) {
resetIntersected()
previousImageSrc.current = src
}
}, [resetIntersected, src])
const imgElementArgs = {
isLazy,
imgAttributes,
heightInt,
widthInt,
qualityInt,
layout,
className,
imgStyle,
blurStyle,
loading,
config,
fill,
unoptimized,
placeholder,
loader,
srcString,
onLoadRef,
onLoadingCompleteRef,
setBlurComplete,
setShowAltText,
setIntersection,
isVisible,
noscriptSizes: sizes,
...rest,
}
return (
<>
{<ImageElement {...imgElementArgs} />}
{
<span style={wrapperStyle}>
{hasSizer ? (
<span style={sizerStyle}>
{sizerSvgUrl ? (
<img
style={{
display: 'block',
maxWidth: '100%',
width: 'initial',
height: 'initial',
background: 'none',
opacity: 1,
border: 0,
margin: 0,
padding: 0,
}}
alt=""
aria-hidden={true}
src={sizerSvgUrl}
/>
) : null}
</span>
) : null}
<ImageElement {...imgElementArgs} />
</span>
}
{priority ? (
// Note how we omit the `href` attribute, as it would only be relevant
// for browsers that do not support `imagesrcset`, and in those cases
......
import Image from '../dist/client/future/image'
export * from '../dist/client/future/image'
export default Image
module.exports = require('../dist/client/future/image')
import Image from '../dist/client/legacy/image'
export * from '../dist/client/legacy/image'
export default Image
module.exports = require('../dist/client/legacy/image')
......@@ -27,6 +27,7 @@
"error.js",
"error.d.ts",
"future",
"legacy",
"script.js",
"script.d.ts",
"server.js",
......
......@@ -132,6 +132,7 @@ export type EventBuildFeatureUsage = {
// *before* you make changes here.
featureName:
| 'next/image'
| 'next/legacy/image'
| 'next/future/image'
| 'next/script'
| 'next/dynamic'
......
......@@ -14,6 +14,7 @@
"./*.d.ts",
"future/*.d.ts",
"image-types/global.d.ts",
"legacy/*.d.ts",
"types/compiled.d.ts"
]
}
......@@ -236,13 +236,20 @@ describe('app dir - rsc basics', () => {
expect(html).toContain('This page could not be found')
})
it('should suspense next/image in server components', async () => {
const imageHTML = await renderViaHTTP(next.url, '/next-api/image')
it('should suspense next/legacy/image in server components', async () => {
const imageHTML = await renderViaHTTP(next.url, '/next-api/image-legacy')
const imageTag = getNodeBySelector(imageHTML, '#myimg')
expect(imageTag.attr('src')).toContain('data:image')
})
it('should suspense next/image in server components', async () => {
const imageHTML = await renderViaHTTP(next.url, '/next-api/image-new')
const imageTag = getNodeBySelector(imageHTML, '#myimg')
expect(imageTag.attr('src')).toMatch(/test.+jpg/)
})
it('should handle various kinds of exports correctly', async () => {
const html = await renderViaHTTP(next.url, '/various-exports')
const content = getNodeBySelector(html, 'body').text()
......
import NextImage from 'next/legacy/image'
import src from '../../../public/test.jpg'
// Keep arrow function to test rsc loaders
const Page = () => {
return <NextImage id="myimg" src={src} />
}
export default Page
......@@ -8,7 +8,6 @@ import {
launchApp,
nextBuild,
nextStart,
renderViaHTTP,
waitFor,
} from 'next-test-utils'
import { join } from 'path'
......@@ -225,33 +224,6 @@ describe('Image Optimizer', () => {
)
})
it('should error when loader=custom but loader prop is undefined', async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
images: {
loader: 'custom',
},
})
)
let output = ''
const appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStderr(msg) {
output += msg || ''
},
onStdout(msg) {
output += msg || ''
},
})
await renderViaHTTP(appPort, '/', {})
await killApp(app).catch(() => {})
await nextConfig.restore()
expect(output).toMatch(
/Error: Image with src "(.+)" is missing "loader" prop/
)
})
it('should error when images.formats contains invalid values', async () => {
await nextConfig.replace(
'{ /* replaceme */ }',
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import img from '../public/test.jpg'
const Page = () => {
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import testTall from './tall.png'
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import React from 'react'
const Page = () => {
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import React from 'react'
import * as styles from './prose.module.css'
......
import Image from 'next/image'
import Image from 'next/legacy/image'
import React from 'react'
const Page = () => {
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import testImg from '../public/foo/test-rect.jpg'
import Image from 'next/image'
import Image from 'next/legacy/image'
import testJPG from '../public/test.jpg'
import testPNG from '../public/test.png'
......
import React, { useState } from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
const [toggled, setToggled] = useState(false)
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
import Link from 'next/link'
const ClientSide = () => {
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Errors = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
import Link from 'next/link'
import Head from 'next/head'
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Lazy = () => {
return (
......
import Image from 'next/image'
import Image from 'next/legacy/image'
const LoaderExample = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const myLoader = ({ src, width, quality }) => {
return `https://customresolver.com/${src}?w~~${width},q~~${quality}`
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
import Link from 'next/link'
const myLoader = ({ src, width, quality }) => {
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import testTall from './tall.png'
......
import React, { useEffect, useState } from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
const [src, setSrc] = useState()
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
export default function Page() {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import React from 'react'
const Page = () => {
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import img from '../public/test.jpg'
const Page = () => {
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import testBMP from '../public/test.bmp'
const Page = () => {
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
export default function Page() {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
import jpg from '../public/test.jpg'
import png from '../public/test.png'
import avif from '../public/test.avif'
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
import img from '../public/test.jpg'
import style from '../style.module.css'
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
const [src, setSrc] = React.useState('/test.jpg')
......
import React, { useRef } from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
const myRef = useRef(null)
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import { useState } from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import { useState } from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
// Hoisted state to count each image load callback
......
import { useState } from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
// Hoisted state to count each image load callback
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import React from 'react'
import * as styles from './prose.module.css'
......
import Image from 'next/image'
import Image from 'next/legacy/image'
import React from 'react'
const Page = () => {
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import Small from '../public/small.jpg'
const Page = () => {
......
import React from 'react'
import testImg from '../public/foo/test-rect.jpg'
import Image from 'next/image'
import Image from 'next/legacy/image'
import testJPG from '../public/test.jpg'
import testPNG from '../public/test.png'
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import style from '../style.module.css'
import img from '../public/test.jpg'
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
import style from '../style.module.css'
const Page = () => {
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React, { useState } from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
const [toggled, setToggled] = useState(false)
......
import Head from 'next/head'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
const Page = () => {
const [count, setCount] = React.useState(0)
......@@ -8,7 +8,7 @@ const Page = () => {
<h1>Warning should print at most once</h1>
<Image
id="w"
layout="unknown"
layout="fixed"
src="/test.png"
width="400"
height="400"
......
......@@ -4,7 +4,7 @@ Object.defineProperty(exports, '__esModule', {
})
exports.default = MyCoolImage
var _jsxRuntime = require('react/jsx-runtime')
var _image = _interopRequireDefault(require('next/future/image'))
var _image = _interopRequireDefault(require('next/legacy/image'))
function _defineProperty(obj, key, value) {
if (key in obj) {
......
......@@ -3,7 +3,7 @@ import MyCoolImage from 'my-cool-image'
const Page = () => {
return (
<div>
<h1>next/image from node_modules</h1>
<h1>next/legacy/image from node_modules</h1>
<MyCoolImage
id="image-from-node-modules"
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const myLoader = ({ src, width, quality }) => {
return `https://customresolver.com${src}?w~~${width},q~~${quality}`
......
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import img from '../public/test.jpg'
import { WindowScroller, List as VirtualizedList } from 'react-virtualized'
......
......@@ -18,7 +18,7 @@ let appPort
let app
let proxyServer: http.Server
let cancelCount = 0
describe('react-virtualized wrapping next/image', () => {
describe('react-virtualized wrapping next/legacy/image', () => {
describe('production', () => {
beforeAll(async () => {
await remove(join(appDir, '.next'))
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import img from '../public/test.jpg'
const Page = () => {
......
import React from 'react'
import Image, { ImageProps } from 'next/image'
import Image, { ImageProps } from 'next/legacy/image'
type ImageCardProps = ImageProps & {
id: string
......
import React from 'react'
import Image, { ImageProps } from 'next/future/image'
import Image, { ImageProps } from 'next/legacy/image'
type DynamicSrcImageProps = ImageProps & {
id: string
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
const Invalid = () => {
return (
......
import React from 'react'
import Image from 'next/image'
import Image from 'next/legacy/image'
import testTall from '../public/tall.png'
import svg from '../public/test.svg'
import avif from '../public/test.avif'
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import img from '../public/äöüščří.png'
const Page = () => {
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/legacy/image'
import testJpg from '../public/test.jpg'
const Page = () => {
......
import React from 'react'
import testImg from '../public/foo/test-rect.jpg'
import Image from 'next/future/image'
import Image from 'next/image'
import testJPG from '../public/test.jpg'
import testPNG from '../public/test.png'
......
......@@ -131,7 +131,7 @@ describe('Build Error Tests', () => {
expect(stderr).not.toContain('Import trace for requested module')
})
})
describe('Future Static Image Component Tests for basePath', () => {
describe('Static Image Component Tests for basePath', () => {
describe('production mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
export default function Page() {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
import test from '../public/test.jpg'
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
export default function Page() {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
export default function Page() {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
import testJPG from '../public/test.jpg'
export default function Page() {
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
export default function Page() {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
export default function Page() {
return (
......
import { useState } from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
const [msg, setMsg] = useState(`default state`)
......
import { useState } from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
const [clicked, setClicked] = useState(false)
......
import { useState } from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
const [idToCount, setIdToCount] = useState({})
......
import { useState } from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
// Hoisted state to count each image load callback
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
import testJPG from '../public/test.jpg'
import testPNG from '../public/test.png'
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
return (
......
import Image from 'next/future/image'
import Image from 'next/image'
import React from 'react'
const Page = () => {
......
import React from 'react'
import testImg from '../public/foo/test-rect.jpg'
import Image from 'next/future/image'
import Image from 'next/image'
import testJPG from '../public/test.jpg'
import testPNG from '../public/test.png'
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
import style from '../style.module.css'
const Page = () => {
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
return (
......
......@@ -8,7 +8,7 @@ const Page = () => {
<h1>Warning should print at most once</h1>
<Image
id="w"
layout="fixed"
layout="unknown"
src="/test.png"
width="400"
height="400"
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Page = () => {
return (
......
......@@ -1204,7 +1204,7 @@ function runTests(mode) {
})
}
describe('Future Image Component Tests', () => {
describe('Image Component Default Tests', () => {
describe('dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
......
......@@ -149,7 +149,7 @@ describe('Build Error Tests', () => {
expect(stderr).not.toContain('Import trace for requested module')
})
})
describe('Future Static Image Component Tests', () => {
describe('Static Image Component Tests', () => {
describe('production mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
......
......@@ -15,7 +15,7 @@ let app
function runTests() {
// This feature was added in PR #31065.
// Skip this test until we promote `next/future/image` from
// Skip this test until we promote `next/image` from
// experimental to stable status.
it.skip('should apply image config for node_modules', async () => {
const browser = await webdriver(appPort, '/')
......@@ -26,7 +26,7 @@ function runTests() {
})
}
describe('Future Image from node_modules prod mode', () => {
describe('Image Component from node_modules prod mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
......@@ -39,7 +39,7 @@ describe('Future Image from node_modules prod mode', () => {
runTests()
})
describe('Future Image from node_modules dev mode', () => {
describe('Image Component from node_modules dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
import test from '../public/invalid.svg'
const Page = () => {
......
import React from 'react'
import Image, { ImageProps } from 'next/future/image'
import Image, { ImageProps } from 'next/image'
type ImageCardProps = ImageProps & {
id: string
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
const Invalid = () => {
return (
......
import React from 'react'
import Image from 'next/future/image'
import Image from 'next/image'
import testTall from '../public/tall.png'
import svg from '../public/test.svg'
import avif from '../public/test.avif'
......
......@@ -6,7 +6,6 @@ module.exports = {
images: {
deviceSizes: [480, 1024, 1600, 2000],
imageSizes: [16, 32, 48, 64],
path: 'https://example.com/myaccount/',
loader: 'imgix',
formats: ['image/avif', 'image/webp'],
},
}
......@@ -12,8 +12,7 @@ export default function Index() {
<Image
id="priority-image"
priority
host="secondary"
src="withpriority2.png"
src="/noop.png"
width={300}
height={400}
/>
......
import Image from 'next/image'
import { Image as FutureImage } from 'next/future/image'
import LegacyImage from 'next/legacy/image'
import profilePic from '../public/small.jpg'
function About() {
......@@ -15,5 +15,5 @@ function About() {
export default About
export function AboutFutureImage() {
return <FutureImage src={profilePic} alt="Picture of the author" />
return <LegacyImage src={profilePic} alt="Picture of the author" />
}
......@@ -838,14 +838,18 @@ describe('Telemetry CLI', () => {
])
})
it('emits telemetry for usage of next/future/image', async () => {
it('emits telemetry for usage of next/legacy/image', async () => {
const { stderr } = await nextBuild(appDir, [], {
stderr: true,
env: { NEXT_TELEMETRY_DEBUG: 1 },
})
const featureUsageEvents = findAllEvents(stderr, 'NEXT_BUILD_FEATURE_USAGE')
expect(featureUsageEvents).toContainEqual({
featureName: 'next/future/image',
featureName: 'next/legacy/image',
invocationCount: 1,
})
expect(featureUsageEvents).toContainEqual({
featureName: 'next/image',
invocationCount: 1,
})
})
......
import React from 'react'
import Image, { ImageProps } from 'next/legacy/image'
export default () => {
const props: ImageProps = {
alt: 'test-width-height',
src: '/noop.jpg',
width: 100,
height: 100,
}
const filledProps: ImageProps = {
alt: 'test-layout-fill',
src: '/noop.jpg',
layout: 'fill',
}
return (
<>
<Image {...props} />
<Image {...filledProps} />
</>
)
}
......@@ -3,14 +3,16 @@ import Image, { ImageProps } from 'next/image'
export default () => {
const props: ImageProps = {
alt: 'test-width-height',
src: '/noop.jpg',
width: 100,
height: 100,
}
const filledProps: ImageProps = {
alt: 'test-fill-true',
src: '/noop.jpg',
layout: 'fill',
fill: true,
}
return (
......
import Image from 'next/image'
import FutureImage from 'next/future/image'
import LegacyImage from 'next/legacy/image'
import png from '../public/test.png'
export default function Page() {
......@@ -8,7 +8,7 @@ export default function Page() {
<h1>Example Image Usage</h1>
<Image src="/test.jpg" width={200} height={200} alt="" />
<hr />
<FutureImage src={png} alt="" />
<LegacyImage src={png} alt="" />
</>
)
}
/* eslint-env jest */
import React from 'react'
import ReactDOM from 'react-dom/server'
import Image from 'next/image'
import Image from 'next/legacy/image'
import cheerio from 'cheerio'
describe('Image rendering', () => {
describe('Image Legacy Rendering', () => {
it('should render Image on its own', async () => {
const element = React.createElement(Image, {
id: 'unit-image',
......
/* eslint-env jest */
import React from 'react'
import ReactDOM from 'react-dom/server'
import Image from 'next/image'
import cheerio from 'cheerio'
describe('Image rendering', () => {
it('should render Image on its own', async () => {
const element = React.createElement(Image, {
alt: 'unit-image',
id: 'unit-image',
src: '/test.png',
width: 100,
height: 100,
loading: 'eager',
})
const html = ReactDOM.renderToString(element)
const $ = cheerio.load(html)
const img = $('#unit-image')
expect(img.attr('id')).toBe('unit-image')
expect(img.attr('src')).toContain('test.png')
expect(img.attr('srcset')).toContain('test.png')
})
it('should only render noscript element when lazy loading', async () => {
const element = React.createElement(Image, {
alt: 'test',
src: '/test.png',
width: 100,
height: 100,
loading: 'eager',
})
const element2 = React.createElement(Image, {
alt: 'test',
src: '/test.png',
width: 100,
height: 100,
priority: true,
})
const elementLazy = React.createElement(Image, {
alt: 'test',
src: '/test.png',
width: 100,
height: 100,
})
const $ = cheerio.load(ReactDOM.renderToString(element))
const $2 = cheerio.load(ReactDOM.renderToString(element2))
const $lazy = cheerio.load(ReactDOM.renderToString(elementLazy))
expect($('noscript').length).toBe(0)
expect($2('noscript').length).toBe(0)
expect($lazy('noscript').length).toBe(0)
})
it('should not render noscript', async () => {
const element1 = React.createElement(Image, {
alt: 'test',
src: '/test.png',
width: 100,
height: 100,
loading: 'eager',
placeholder: 'blur',
blurDataURL: 'data:image/png;base64',
})
const element2 = React.createElement(Image, {
alt: 'test',
src: '/test.png',
width: 100,
height: 100,
placeholder: 'blur',
blurDataURL: 'data:image/png;base64',
loading: 'eager',
})
const element3 = React.createElement(Image, {
alt: 'test',
src: '/test.png',
width: 100,
height: 100,
placeholder: 'blur',
blurDataURL: 'data:image/png;base64',
priority: true,
})
const $1 = cheerio.load(ReactDOM.renderToString(element1))
const $2 = cheerio.load(ReactDOM.renderToString(element2))
const $3 = cheerio.load(ReactDOM.renderToString(element3))
expect($1('noscript').length).toBe(0)
expect($2('noscript').length).toBe(0)
expect($3('noscript').length).toBe(0)
})
})
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