Unverified Commit 7f677d1e authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Revert "[image, link] fix ref merging for callback refs that return a cleanup function" (#68176)

Seems this is causing us to hit the following error our vercel-site

```sh
 ReferenceError: navigator is not defined
vercel-site:build:     at s (/vercel/path0/apps/vercel-site/.next/server/chunks-EDOwHfQ0FCxDTUqmP-83_/65787.js:161:168406)
vercel-site:build:     at u (/vercel/path0/apps/vercel-site/.next/server/chunks-EDOwHfQ0FCxDTUqmP-83_/65787.js:50:154810)
```

Reverts vercel/next.js#68123
parent 7b14e206
...@@ -31,7 +31,6 @@ import { RouterContext } from '../shared/lib/router-context.shared-runtime' ...@@ -31,7 +31,6 @@ import { RouterContext } from '../shared/lib/router-context.shared-runtime'
// @ts-ignore - This is replaced by webpack alias // @ts-ignore - This is replaced by webpack alias
import defaultLoader from 'next/dist/shared/lib/image-loader' import defaultLoader from 'next/dist/shared/lib/image-loader'
import { useMergedRef } from './use-merged-ref'
// This is replaced by webpack define plugin // This is replaced by webpack define plugin
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete
...@@ -207,8 +206,38 @@ const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>( ...@@ -207,8 +206,38 @@ const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>(
}, },
forwardedRef forwardedRef
) => { ) => {
const ownRef = useCallback( return (
<img
{...rest}
{...getDynamicProps(fetchPriority)}
// It's intended to keep `loading` before `src` because React updates
// props in order which causes Safari/Firefox to not lazy load properly.
// See https://github.com/facebook/react/issues/25883
loading={loading}
width={width}
height={height}
decoding={decoding}
data-nimg={fill ? 'fill' : '1'}
className={className}
style={style}
// It's intended to keep `src` the last attribute because React updates
// attributes in order. If we keep `src` the first one, Safari will
// immediately start to fetch `src`, before `sizes` and `srcSet` are even
// updated by React. That causes multiple unnecessary requests if `srcSet`
// and `sizes` are defined.
// This bug cannot be reproduced in Chrome or Firefox.
sizes={sizes}
srcSet={srcSet}
src={src}
ref={useCallback(
(img: ImgElementWithDataProp | null) => { (img: ImgElementWithDataProp | null) => {
if (forwardedRef) {
if (typeof forwardedRef === 'function') forwardedRef(img)
else if (typeof forwardedRef === 'object') {
// @ts-ignore - .current is read only it's usually assigned by react internally
forwardedRef.current = img
}
}
if (!img) { if (!img) {
return return
} }
...@@ -250,35 +279,9 @@ const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>( ...@@ -250,35 +279,9 @@ const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>(
onError, onError,
unoptimized, unoptimized,
sizesInput, sizesInput,
forwardedRef,
] ]
) )}
const ref = useMergedRef(forwardedRef, ownRef)
return (
<img
{...rest}
{...getDynamicProps(fetchPriority)}
// It's intended to keep `loading` before `src` because React updates
// props in order which causes Safari/Firefox to not lazy load properly.
// See https://github.com/facebook/react/issues/25883
loading={loading}
width={width}
height={height}
decoding={decoding}
data-nimg={fill ? 'fill' : '1'}
className={className}
style={style}
// It's intended to keep `src` the last attribute because React updates
// attributes in order. If we keep `src` the first one, Safari will
// immediately start to fetch `src`, before `sizes` and `srcSet` are even
// updated by React. That causes multiple unnecessary requests if `srcSet`
// and `sizes` are defined.
// This bug cannot be reproduced in Chrome or Firefox.
sizes={sizes}
srcSet={srcSet}
src={src}
ref={ref}
onLoad={(event) => { onLoad={(event) => {
const img = event.currentTarget as ImgElementWithDataProp const img = event.currentTarget as ImgElementWithDataProp
handleLoading( handleLoading(
......
...@@ -22,7 +22,6 @@ import { useIntersection } from './use-intersection' ...@@ -22,7 +22,6 @@ import { useIntersection } from './use-intersection'
import { getDomainLocale } from './get-domain-locale' import { getDomainLocale } from './get-domain-locale'
import { addBasePath } from './add-base-path' import { addBasePath } from './add-base-path'
import { PrefetchKind } from './components/router-reducer/router-reducer-types' import { PrefetchKind } from './components/router-reducer/router-reducer-types'
import { useMergedRef } from './use-merged-ref'
type Url = string | UrlObject type Url = string | UrlObject
type RequiredKeys<T> = { type RequiredKeys<T> = {
...@@ -547,7 +546,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -547,7 +546,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
rootMargin: '200px', rootMargin: '200px',
}) })
const setIntersectionWithResetRef = React.useCallback( const setRef = React.useCallback(
(el: Element) => { (el: Element) => {
// Before the link getting observed, check if visible state need to be reset // Before the link getting observed, check if visible state need to be reset
if (previousAs.current !== as || previousHref.current !== href) { if (previousAs.current !== as || previousHref.current !== href) {
...@@ -557,12 +556,16 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -557,12 +556,16 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
} }
setIntersectionRef(el) setIntersectionRef(el)
if (childRef) {
if (typeof childRef === 'function') childRef(el)
else if (typeof childRef === 'object') {
childRef.current = el
}
}
}, },
[as, href, resetVisible, setIntersectionRef] [as, childRef, href, resetVisible, setIntersectionRef]
) )
const setRef = useMergedRef(setIntersectionWithResetRef, childRef)
// Prefetch the URL if we haven't already and it's visible. // Prefetch the URL if we haven't already and it's visible.
React.useEffect(() => { React.useEffect(() => {
// in dev, we only prefetch on hover to avoid wasting resources as the prefetch will trigger compiling the page. // in dev, we only prefetch on hover to avoid wasting resources as the prefetch will trigger compiling the page.
......
import { useMemo, type Ref } from 'react'
export function useMergedRef<TElement>(
refA: Ref<TElement>,
refB: Ref<TElement>
): Ref<TElement> {
return useMemo(() => mergeRefs(refA, refB), [refA, refB])
}
export function mergeRefs<TElement>(
refA: Ref<TElement>,
refB: Ref<TElement>
): Ref<TElement> {
if (!refA || !refB) {
return refA || refB
}
return (current: TElement) => {
const cleanupA = applyRef(refA, current)
const cleanupB = applyRef(refB, current)
return () => {
cleanupA()
cleanupB()
}
}
}
function applyRef<TElement>(
refA: NonNullable<Ref<TElement>>,
current: TElement
) {
if (typeof refA === 'function') {
const cleanup = refA(current)
if (typeof cleanup === 'function') {
return cleanup
} else {
return () => refA(null)
}
} else {
refA.current = current
return () => {
refA.current = null
}
}
}
import React from 'react'
import Link from 'next/link'
import { useCallback, useRef, useEffect, useState } from 'react'
import { flushSync } from 'react-dom'
export default function Page() {
const [isVisible, setIsVisible] = useState(true)
const statusRef = useRef({ wasInitialized: false, wasCleanedUp: false })
const refWithCleanup = useCallback((el) => {
if (!el) {
console.error(
'callback refs that returned a cleanup should never be called with null'
)
return
}
statusRef.current.wasInitialized = true
return () => {
statusRef.current.wasCleanedUp = true
}
}, [])
useEffect(() => {
const timeout = setTimeout(
() => {
flushSync(() => {
setIsVisible(false)
})
if (!statusRef.current.wasInitialized) {
console.error('callback ref was not initialized')
}
if (!statusRef.current.wasCleanedUp) {
console.error('callback ref was not cleaned up')
}
},
100 // if we hide the Link too quickly, the prefetch won't fire, failing a test
)
return () => clearTimeout(timeout)
}, [])
if (!isVisible) {
return null
}
return (
<Link href="/" ref={refWithCleanup}>
Click me
</Link>
)
}
...@@ -84,10 +84,6 @@ describe('Invalid hrefs', () => { ...@@ -84,10 +84,6 @@ describe('Invalid hrefs', () => {
it('should handle child ref that is a function', async () => { it('should handle child ref that is a function', async () => {
await noError('/child-ref-func') await noError('/child-ref-func')
}) })
it('should handle child ref that is a function that returns a cleanup function', async () => {
await noError('/child-ref-func-cleanup')
})
} }
) )
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
...@@ -113,10 +109,6 @@ describe('Invalid hrefs', () => { ...@@ -113,10 +109,6 @@ describe('Invalid hrefs', () => {
it('should preload with child ref with function', async () => { it('should preload with child ref with function', async () => {
await didPrefetch('/child-ref-func') await didPrefetch('/child-ref-func')
}) })
it('should preload with child ref with function that returns a cleanup function', async () => {
await didPrefetch('/child-ref-func-cleanup')
})
} }
) )
}) })
'use client'
import Image from 'next/image'
import { useCallback, useEffect, useState } from 'react'
export default function Home() {
const [displayImage, setDisplayImage] = useState(true)
const refWithCleanup = useCallback((el) => {
if (!el) {
throw new Error(
'callback refs that returned a cleanup should never be called with null'
)
}
return () => {
console.log('callback ref was cleaned up')
}
}, [])
useEffect(() => {
setDisplayImage(false)
}, [])
return (
<main>
<h1>Should call ref cleanup on unmount</h1>
<section>
{displayImage ? (
<div style={{ position: 'relative', width: 10, height: 10 }}>
<Image
ref={refWithCleanup}
priority
fill
src="/test.jpg"
alt="alt"
sizes="10px"
/>
</div>
) : null}
</section>
</main>
)
}
...@@ -14,7 +14,6 @@ import { ...@@ -14,7 +14,6 @@ import {
nextBuild, nextBuild,
nextStart, nextStart,
renderViaHTTP, renderViaHTTP,
retry,
waitFor, waitFor,
} from 'next-test-utils' } from 'next-test-utils'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
...@@ -1575,19 +1574,6 @@ function runTests(mode) { ...@@ -1575,19 +1574,6 @@ function runTests(mode) {
} }
} }
}) })
it('should call callback ref cleanups when unmounting', async () => {
const browser = await webdriver(appPort, '/ref-cleanup')
const getLogs = async () => (await browser.log()).map((log) => log.message)
await retry(async () => {
expect(await getLogs()).toContain('callback ref was cleaned up')
})
expect(await getLogs()).not.toContain(
'callback refs that returned a cleanup should never be called with null'
)
})
} }
describe('Image Component Default Tests', () => { describe('Image Component Default Tests', () => {
......
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