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

Fix multiple calls to image `onLoadingComplete()` (#33474)

The image prop `onLoadingComplete()` was unexpectedly called multiple times because it uses a [callback ref](https://reactjs.org/docs/refs-and-the-dom.html#callback-refs).

This could lead to an infinite loop if `onLoadingComplete()` calls `setState()` as demonstrated in the updated test.

The solution is to handle refs with `useRef()` and `useEffect` so `onLoadingComplete()` is called at most once per component instance.

- Fixes #33463 
parent 96057c8f
import React from 'react' import React, { useRef, useEffect } from 'react'
import Head from '../shared/lib/head' import Head from '../shared/lib/head'
import { import {
ImageConfigComplete, ImageConfigComplete,
...@@ -8,7 +8,6 @@ import { ...@@ -8,7 +8,6 @@ import {
} from '../server/image-config' } from '../server/image-config'
import { useIntersection } from './use-intersection' import { useIntersection } from './use-intersection'
const loadedImageURLs = new Set<string>()
const allImgs = new Map< const allImgs = new Map<
string, string,
{ src: string; priority: boolean; placeholder: string } { src: string; priority: boolean; placeholder: string }
...@@ -250,31 +249,34 @@ function defaultImageLoader(loaderProps: ImageLoaderProps) { ...@@ -250,31 +249,34 @@ function defaultImageLoader(loaderProps: ImageLoaderProps) {
// See https://stackoverflow.com/q/39777833/266535 for why we use this ref // See https://stackoverflow.com/q/39777833/266535 for why we use this ref
// handler instead of the img's onLoad attribute. // handler instead of the img's onLoad attribute.
function handleLoading( function handleLoading(
img: HTMLImageElement | null, imgRef: React.RefObject<HTMLImageElement>,
src: string, src: string,
layout: LayoutValue, layout: LayoutValue,
placeholder: PlaceholderValue, placeholder: PlaceholderValue,
onLoadingComplete?: OnLoadingComplete onLoadingCompleteRef: React.MutableRefObject<OnLoadingComplete | undefined>
) { ) {
const handleLoad = () => {
const img = imgRef.current
if (!img) { if (!img) {
return return
} }
const handleLoad = () => {
if (img.src !== emptyDataURL) { if (img.src !== emptyDataURL) {
const p = 'decode' in img ? img.decode() : Promise.resolve() const p = 'decode' in img ? img.decode() : Promise.resolve()
p.catch(() => {}).then(() => { p.catch(() => {}).then(() => {
if (!imgRef.current) {
return
}
if (placeholder === 'blur') { if (placeholder === 'blur') {
img.style.filter = '' img.style.filter = ''
img.style.backgroundSize = '' img.style.backgroundSize = ''
img.style.backgroundImage = '' img.style.backgroundImage = ''
img.style.backgroundPosition = '' img.style.backgroundPosition = ''
} }
loadedImageURLs.add(src) if (onLoadingCompleteRef.current) {
if (onLoadingComplete) {
const { naturalWidth, naturalHeight } = img const { naturalWidth, naturalHeight } = img
// Pass back read-only primitive values but not the // Pass back read-only primitive values but not the
// underlying DOM element because it could be misused. // underlying DOM element because it could be misused.
onLoadingComplete({ naturalWidth, naturalHeight }) onLoadingCompleteRef.current({ naturalWidth, naturalHeight })
} }
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (img.parentElement?.parentElement) { if (img.parentElement?.parentElement) {
...@@ -299,13 +301,15 @@ function handleLoading( ...@@ -299,13 +301,15 @@ function handleLoading(
}) })
} }
} }
if (img.complete) { if (imgRef.current) {
if (imgRef.current.complete) {
// If the real image fails to load, this will still remove the placeholder. // If the real image fails to load, this will still remove the placeholder.
// This is the desired behavior for now, and will be revisited when error // This is the desired behavior for now, and will be revisited when error
// handling is worked on for the image component itself. // handling is worked on for the image component itself.
handleLoad() handleLoad()
} else { } else {
img.onload = handleLoad imgRef.current.onload = handleLoad
}
} }
} }
...@@ -328,6 +332,7 @@ export default function Image({ ...@@ -328,6 +332,7 @@ export default function Image({
blurDataURL, blurDataURL,
...all ...all
}: ImageProps) { }: ImageProps) {
const imgRef = useRef<HTMLImageElement>(null)
let rest: Partial<ImageProps> = all let rest: Partial<ImageProps> = all
let layout: NonNullable<LayoutValue> = sizes ? 'responsive' : 'intrinsic' let layout: NonNullable<LayoutValue> = sizes ? 'responsive' : 'intrinsic'
if ('layout' in rest) { if ('layout' in rest) {
...@@ -376,7 +381,7 @@ export default function Image({ ...@@ -376,7 +381,7 @@ export default function Image({
unoptimized = true unoptimized = true
isLazy = false isLazy = false
} }
if (typeof window !== 'undefined' && loadedImageURLs.has(src)) { if (typeof window !== 'undefined' && imgRef.current?.complete) {
isLazy = false isLazy = false
} }
...@@ -504,7 +509,7 @@ export default function Image({ ...@@ -504,7 +509,7 @@ export default function Image({
} }
} }
const [setRef, isIntersected] = useIntersection<HTMLImageElement>({ const [setIntersection, isIntersected] = useIntersection<HTMLImageElement>({
rootMargin: lazyBoundary, rootMargin: lazyBoundary,
disabled: !isLazy, disabled: !isLazy,
}) })
...@@ -657,6 +662,22 @@ export default function Image({ ...@@ -657,6 +662,22 @@ export default function Image({
[imageSizesPropName]: imgAttributes.sizes, [imageSizesPropName]: imgAttributes.sizes,
} }
const useLayoutEffect =
typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect
const onLoadingCompleteRef = useRef(onLoadingComplete)
useEffect(() => {
onLoadingCompleteRef.current = onLoadingComplete
}, [onLoadingComplete])
useLayoutEffect(() => {
setIntersection(imgRef.current)
}, [setIntersection])
useEffect(() => {
handleLoading(imgRef, srcString, layout, placeholder, onLoadingCompleteRef)
}, [srcString, layout, placeholder, isVisible])
return ( return (
<span style={wrapperStyle}> <span style={wrapperStyle}>
{hasSizer ? ( {hasSizer ? (
...@@ -687,10 +708,7 @@ export default function Image({ ...@@ -687,10 +708,7 @@ export default function Image({
decoding="async" decoding="async"
data-nimg={layout} data-nimg={layout}
className={className} className={className}
ref={(img) => { ref={imgRef}
setRef(img)
handleLoading(img, srcString, layout, placeholder, onLoadingComplete)
}}
style={{ ...imgStyle, ...blurStyle }} style={{ ...imgStyle, ...blurStyle }}
/> />
{isLazy && ( {isLazy && (
......
import { useState } from 'react' import { useState } from 'react'
import Image from 'next/image' import Image from 'next/image'
const Page = () => ( const Page = () => {
// Hoisted state to count each image load callback
const [idToCount, setIdToCount] = useState({})
const [clicked, setClicked] = useState(false)
return (
<div> <div>
<h1>On Loading Complete Test</h1> <h1>On Loading Complete Test</h1>
<ImageWithMessage <ImageWithMessage
...@@ -10,65 +15,108 @@ const Page = () => ( ...@@ -10,65 +15,108 @@ const Page = () => (
layout="intrinsic" layout="intrinsic"
width="128" width="128"
height="128" height="128"
idToCount={idToCount}
setIdToCount={setIdToCount}
/> />
<hr />
<ImageWithMessage <ImageWithMessage
id="2" id="2"
src={require('../public/test.png')} src={require('../public/test.png')}
placeholder="blur" placeholder="blur"
layout="fixed" layout="fixed"
idToCount={idToCount}
setIdToCount={setIdToCount}
/> />
<hr />
<ImageWithMessage <ImageWithMessage
id="3" id="3"
src="/test.svg" src="/test.svg"
layout="responsive" layout="responsive"
width="1200" width="1200"
height="1200" height="1200"
idToCount={idToCount}
setIdToCount={setIdToCount}
/> />
<hr />
<div style={{ position: 'relative', width: '64px', height: '64px' }}>
<ImageWithMessage <ImageWithMessage
id="4" id="4"
src="/test.ico" src="/test.ico"
layout="fill" layout="fill"
objectFit="contain" objectFit="contain"
idToCount={idToCount}
setIdToCount={setIdToCount}
/> />
</div>
<hr />
<ImageWithMessage <ImageWithMessage
id="5" id="5"
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAE0lEQVR42mNk+P+/ngEKGMngAADDdwx3Uz/3AAAAAABJRU5ErkJggg==" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAE0lEQVR42mNk+P+/ngEKGMngAADDdwx3Uz/3AAAAAABJRU5ErkJggg=="
layout="fixed" layout="fixed"
width={64} width={64}
height={64} height={64}
idToCount={idToCount}
setIdToCount={setIdToCount}
/> />
<hr />
<div style={{ position: 'relative', width: '64px', height: '64px' }}>
<ImageWithMessage <ImageWithMessage
id="6" id="6"
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAE0lEQVR42mNk+P+/ngEKGMngAADDdwx3Uz/3AAAAAABJRU5ErkJggg==" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAE0lEQVR42mNk+P+/ngEKGMngAADDdwx3Uz/3AAAAAABJRU5ErkJggg=="
layout="fill" layout="fill"
idToCount={idToCount}
setIdToCount={setIdToCount}
/> />
</div>
<ImageWithMessage
id="7"
src="/test.bmp"
loading="eager"
width="400"
height="400"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<ImageWithMessage
id="8"
src={clicked ? '/foo/test-rect.jpg' : '/wide.png'}
layout={clicked ? 'fixed' : 'intrinsic'}
width="500"
height="500"
idToCount={idToCount}
setIdToCount={setIdToCount}
/>
<button id="toggle" onClick={() => setClicked(!clicked)}>
Toggle
</button>
<div id="footer" /> <div id="footer" />
</div> </div>
) )
}
function ImageWithMessage({ id, ...props }) { function ImageWithMessage({ id, idToCount, setIdToCount, ...props }) {
const [msg, setMsg] = useState('[LOADING]') const [msg, setMsg] = useState('[LOADING]')
const style =
props.layout === 'fill'
? { position: 'relative', width: '64px', height: '64px' }
: {}
return ( return (
<> <>
<div className="wrap" style={style}>
<Image <Image
id={`img${id}`} id={`img${id}`}
onLoadingComplete={({ naturalWidth, naturalHeight }) => onLoadingComplete={({ naturalWidth, naturalHeight }) => {
setMsg( let count = idToCount[id] || 0
`loaded img${id} with dimensions ${naturalWidth}x${naturalHeight}` count++
) idToCount[id] = count
} setIdToCount(idToCount)
const msg = `loaded ${count} img${id} with dimensions ${naturalWidth}x${naturalHeight}`
setMsg(msg)
console.log(msg)
}}
{...props} {...props}
/> />
</div>
<p id={`msg${id}`}>{msg}</p> <p id={`msg${id}`}>{msg}</p>
<hr />
</> </>
) )
} }
......
...@@ -193,47 +193,84 @@ function runTests(mode) { ...@@ -193,47 +193,84 @@ function runTests(mode) {
try { try {
browser = await webdriver(appPort, '/on-loading-complete') browser = await webdriver(appPort, '/on-loading-complete')
await browser.eval(`document.getElementById("footer").scrollIntoView()`) await browser.eval(
`document.getElementById("footer").scrollIntoView({behavior: "smooth"})`
)
await check( await check(
() => browser.eval(`document.getElementById("img1").src`), () => browser.eval(`document.getElementById("img1").currentSrc`),
/test(.*)jpg/ /test(.*)jpg/
) )
await check( await check(
() => browser.eval(`document.getElementById("img2").src`), () => browser.eval(`document.getElementById("img2").currentSrc`),
/test(.*).png/ /test(.*).png/
) )
await check( await check(
() => browser.eval(`document.getElementById("img3").src`), () => browser.eval(`document.getElementById("img3").currentSrc`),
/test(.*)svg/ /test(.*)svg/
) )
await check( await check(
() => browser.eval(`document.getElementById("img4").src`), () => browser.eval(`document.getElementById("img4").currentSrc`),
/test(.*)ico/ /test(.*)ico/
) )
await check( await check(
() => browser.eval(`document.getElementById("msg1").textContent`), () => browser.eval(`document.getElementById("msg1").textContent`),
'loaded img1 with dimensions 128x128' 'loaded 1 img1 with dimensions 128x128'
) )
await check( await check(
() => browser.eval(`document.getElementById("msg2").textContent`), () => browser.eval(`document.getElementById("msg2").textContent`),
'loaded img2 with dimensions 400x400' 'loaded 1 img2 with dimensions 400x400'
) )
await check( await check(
() => browser.eval(`document.getElementById("msg3").textContent`), () => browser.eval(`document.getElementById("msg3").textContent`),
'loaded img3 with dimensions 266x266' 'loaded 1 img3 with dimensions 266x266'
) )
await check( await check(
() => browser.eval(`document.getElementById("msg4").textContent`), () => browser.eval(`document.getElementById("msg4").textContent`),
'loaded img4 with dimensions 21x21' 'loaded 1 img4 with dimensions 21x21'
) )
await check( await check(
() => browser.eval(`document.getElementById("msg5").textContent`), () => browser.eval(`document.getElementById("msg5").textContent`),
'loaded img5 with dimensions 3x5' 'loaded 1 img5 with dimensions 3x5'
) )
await check( await check(
() => browser.eval(`document.getElementById("msg6").textContent`), () => browser.eval(`document.getElementById("msg6").textContent`),
'loaded img6 with dimensions 3x5' 'loaded 1 img6 with dimensions 3x5'
)
await check(
() => browser.eval(`document.getElementById("msg7").textContent`),
'loaded 1 img7 with dimensions 400x400'
)
await check(
() => browser.eval(`document.getElementById("msg8").textContent`),
'loaded 1 img8 with dimensions 640x373'
)
await check(
() =>
browser.eval(
`document.getElementById("img8").getAttribute("data-nimg")`
),
'intrinsic'
)
await check(
() => browser.eval(`document.getElementById("img8").currentSrc`),
/wide.png/
)
await browser.eval('document.getElementById("toggle").click()')
await check(
() => browser.eval(`document.getElementById("msg8").textContent`),
'loaded 2 img8 with dimensions 400x300'
)
await check(
() =>
browser.eval(
`document.getElementById("img8").getAttribute("data-nimg")`
),
'fixed'
)
await check(
() => browser.eval(`document.getElementById("img8").currentSrc`),
/test-rect.jpg/
) )
} finally { } finally {
if (browser) { if (browser) {
......
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