Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: reset visible state when src/href changed #35287

Merged
merged 6 commits into from Apr 4, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 13 additions & 7 deletions packages/next/client/image.tsx
Expand Up @@ -417,11 +417,12 @@ export default function Image({
isLazy = false
}

const [setIntersection, isIntersected] = useIntersection<HTMLImageElement>({
rootRef: lazyRoot,
rootMargin: lazyBoundary,
disabled: !isLazy,
})
const [setIntersection, isIntersected, resetIntersected] =
useIntersection<HTMLImageElement>({
rootRef: lazyRoot,
rootMargin: lazyBoundary,
disabled: !isLazy,
})
const isVisible = !isLazy || isIntersected

const wrapperStyle: JSX.IntrinsicElements['span']['style'] = {
Expand Down Expand Up @@ -639,7 +640,6 @@ export default function Image({
? { aspectRatio: `${widthInt} / ${heightInt}` }
: layoutStyle
)

const blurStyle =
placeholder === 'blur'
? {
Expand Down Expand Up @@ -743,14 +743,20 @@ export default function Image({
typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect
const onLoadingCompleteRef = useRef(onLoadingComplete)

const previousImageSrc = useRef<string | StaticImport>(src)
const imgRef = useRef<HTMLImageElement>(null)
useEffect(() => {
onLoadingCompleteRef.current = onLoadingComplete
}, [onLoadingComplete])

useLayoutEffect(() => {
if (previousImageSrc.current !== src) {
resetIntersected()
previousImageSrc.current = src
}

setIntersection(imgRef.current)
}, [setIntersection])
}, [setIntersection, resetIntersected, src])

useEffect(() => {
handleLoading(imgRef, srcString, layout, placeholder, onLoadingCompleteRef)
Expand Down
15 changes: 13 additions & 2 deletions packages/next/client/link.tsx
Expand Up @@ -219,6 +219,9 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
}
}, [router, props.href, props.as])

const previousHref = React.useRef<string>(href)
const previousAs = React.useRef<string>(as)

let { children, replace, shallow, scroll, locale } = props

if (typeof children === 'string') {
Expand All @@ -243,11 +246,19 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
}
const childRef: any = child && typeof child === 'object' && child.ref

const [setIntersectionRef, isVisible] = useIntersection({
const [setIntersectionRef, isVisible, resetVisible] = useIntersection({
rootMargin: '200px',
})

const setRef = React.useCallback(
(el: Element) => {
// Before the link getting observed, check if visible state need to be reset
if (previousAs.current !== as || previousHref.current !== href) {
resetVisible()
previousAs.current = as
previousHref.current = href
}

setIntersectionRef(el)
if (childRef) {
if (typeof childRef === 'function') childRef(el)
Expand All @@ -256,7 +267,7 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
}
}
},
[childRef, setIntersectionRef]
[as, childRef, href, resetVisible, setIntersectionRef]
)
React.useEffect(() => {
const shouldPrefetch = isVisible && p && isLocalURL(href)
Expand Down
8 changes: 6 additions & 2 deletions packages/next/client/use-intersection.tsx
Expand Up @@ -29,7 +29,7 @@ export function useIntersection<T extends Element>({
rootRef,
rootMargin,
disabled,
}: UseIntersection): [(element: T | null) => void, boolean] {
}: UseIntersection): [(element: T | null) => void, boolean, () => void] {
const isDisabled: boolean = disabled || !hasIntersectionObserver

const unobserve = useRef<Function>()
Expand All @@ -55,6 +55,10 @@ export function useIntersection<T extends Element>({
[isDisabled, root, rootMargin, visible]
)

const resetVisible = useCallback(() => {
setVisible(false)
}, [])

useEffect(() => {
if (!hasIntersectionObserver) {
if (!visible) {
Expand All @@ -67,7 +71,7 @@ export function useIntersection<T extends Element>({
useEffect(() => {
if (rootRef) setRoot(rootRef.current)
}, [rootRef])
return [setRef, visible]
return [setRef, visible, resetVisible]
}

function observe(
Expand Down
@@ -0,0 +1,21 @@
import React from 'react'
import Image from 'next/image'

const Page = () => {
const [src, setSrc] = React.useState('/test.jpg')
styfle marked this conversation as resolved.
Show resolved Hide resolved
return (
<div>
<p>Home Page</p>
<div id="spacer" style={{ height: '150vh' }} />
<Image id="basic-image" src={src} width="400" height="400"></Image>
<button
id="button-change-image-src"
onClick={() => setSrc('/test.jpg?new')}
SukkaW marked this conversation as resolved.
Show resolved Hide resolved
>
Change Image
</button>
</div>
)
}

export default Page
81 changes: 81 additions & 0 deletions test/integration/image-component/default/test/index.test.js
Expand Up @@ -1173,6 +1173,87 @@ function runTests(mode) {
}
})

it('should re-lazyload images after src changes', async () => {
let browser
try {
browser = await webdriver(appPort, '/lazy-src-change')

// image should not be loaded as it is out of viewport
await check(async () => {
const result = await browser.eval(
`document.getElementById('basic-image').naturalWidth`
)

if (result >= 400) {
throw new Error('Incorrectly loaded image')
}

return 'result-correct'
}, /result-correct/)

// Move image into viewport
await browser.eval(
'document.getElementById("spacer").style.display = "none"'
)

// image should be loaded by now
SukkaW marked this conversation as resolved.
Show resolved Hide resolved
await check(async () => {
const result = await browser.eval(
`document.getElementById('basic-image').naturalWidth`
)

if (result < 400) {
throw new Error('Incorrectly loaded image')
}

return 'result-correct'
}, /result-correct/)

// Make image out of viewport again
await browser.eval(
'document.getElementById("spacer").style.display = "block"'
)
// Toggle image's src
await browser.eval(
'document.getElementById("button-change-image-src").click()'
)

// "new" image should be lazy loaded
SukkaW marked this conversation as resolved.
Show resolved Hide resolved
await check(async () => {
const result = await browser.eval(
`document.getElementById('basic-image').naturalWidth`
)

if (result >= 400) {
throw new Error('Incorrectly loaded image')
}

return 'result-correct'
}, /result-correct/)

// Move image into viewport again
await browser.eval(
'document.getElementById("spacer").style.display = "none"'
)
// "new" image should be loaded by now
await check(async () => {
const result = await browser.eval(
`document.getElementById('basic-image').naturalWidth`
)

if (result >= 400) {
throw new Error('Incorrectly loaded image')
}

return 'result-correct'
}, /result-correct/)
} finally {
if (browser) {
await browser.close()
}
}
})

it('should initially load only two of four images using lazyroot', async () => {
let browser
try {
Expand Down