Unverified Commit ad728f4e authored by Sukka's avatar Sukka Committed by GitHub

Fix `<Image/>`'s `lazyRoot` and other optimizations (#37447)



The PR fixes `<Image />` and `<Link />` components' extra re-renders, `lazyRoot` has no effect, and applies some other optimizations.
parent eb9a500d
......@@ -23,7 +23,7 @@ type Observer = {
elements: Map<Element, ObserveCallback>
}
const hasIntersectionObserver = typeof IntersectionObserver !== 'undefined'
const hasIntersectionObserver = typeof IntersectionObserver === 'function'
export function useIntersection<T extends Element>({
rootRef,
......@@ -34,9 +34,10 @@ export function useIntersection<T extends Element>({
const unobserve = useRef<Function>()
const [visible, setVisible] = useState(false)
const [root, setRoot] = useState(rootRef ? rootRef.current : null)
const setRef = useCallback(
(el: T | null) => {
const [element, setElement] = useState<T | null>(null)
useEffect(() => {
if (hasIntersectionObserver) {
if (unobserve.current) {
unobserve.current()
unobserve.current = undefined
......@@ -44,34 +45,31 @@ export function useIntersection<T extends Element>({
if (isDisabled || visible) return
if (el && el.tagName) {
if (element && element.tagName) {
unobserve.current = observe(
el,
element,
(isVisible) => isVisible && setVisible(isVisible),
{ root, rootMargin }
{ root: rootRef?.current, rootMargin }
)
}
},
[isDisabled, root, rootMargin, visible]
)
const resetVisible = useCallback(() => {
setVisible(false)
}, [])
useEffect(() => {
if (!hasIntersectionObserver) {
return () => {
unobserve.current?.()
unobserve.current = undefined
}
} else {
if (!visible) {
const idleCallback = requestIdleCallback(() => setVisible(true))
return () => cancelIdleCallback(idleCallback)
}
}
}, [visible])
}, [element, isDisabled, rootMargin, rootRef, visible])
useEffect(() => {
if (rootRef) setRoot(rootRef.current)
}, [rootRef])
return [setRef, visible, resetVisible]
const resetVisible = useCallback(() => {
setVisible(false)
}, [])
return [setElement, visible, resetVisible]
}
function observe(
......@@ -91,7 +89,7 @@ function observe(
if (elements.size === 0) {
observer.disconnect()
observers.delete(id)
let index = idList.findIndex(
const index = idList.findIndex(
(obj) => obj.root === id.root && obj.margin === id.margin
)
if (index > -1) {
......@@ -110,18 +108,16 @@ function createObserver(options: UseIntersectionObserverInit): Observer {
root: options.root || null,
margin: options.rootMargin || '',
}
let existing = idList.find(
const existing = idList.find(
(obj) => obj.root === id.root && obj.margin === id.margin
)
let instance
let instance: Observer | undefined
if (existing) {
instance = observers.get(existing)
} else {
instance = observers.get(id)
idList.push(id)
}
if (instance) {
return instance
if (instance) {
return instance
}
}
const elements = new Map<Element, ObserveCallback>()
......@@ -134,14 +130,13 @@ function createObserver(options: UseIntersectionObserverInit): Observer {
}
})
}, options)
observers.set(
instance = {
id,
(instance = {
id,
observer,
elements,
})
)
observer,
elements,
}
idList.push(id)
observers.set(id, instance)
return instance
}
import React from 'react'
import Image from 'next/image'
import Link from 'next/link'
const Lazy = () => {
return (
......@@ -54,9 +53,6 @@ const Lazy = () => {
width={800}
lazyBoundary="0px 0px 500px 0px"
></Image>
<Link href="/missing-observer">
<a id="observerlink">observer</a>
</Link>
</div>
)
}
......
......@@ -384,19 +384,6 @@ describe('Image Component Tests', () => {
browser = null
})
lazyLoadingTests()
it('should automatically load images if observer does not exist', async () => {
browser = await webdriver(appPort, '/missing-observer')
expect(
await browser.elementById('lazy-no-observer').getAttribute('src')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000'
)
expect(
await browser.elementById('lazy-no-observer').getAttribute('srcset')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=1024 1x, https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000 2x'
)
})
})
describe('Client-side Lazy Loading Tests', () => {
beforeAll(async () => {
......@@ -408,20 +395,5 @@ describe('Image Component Tests', () => {
browser = null
})
lazyLoadingTests()
it('should automatically load images if observer does not exist', async () => {
await browser.waitForElementByCss('#observerlink').click()
await waitFor(500)
browser = await webdriver(appPort, '/missing-observer')
expect(
await browser.elementById('lazy-no-observer').getAttribute('src')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000'
)
expect(
await browser.elementById('lazy-no-observer').getAttribute('srcset')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=1024 1x, https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000 2x'
)
})
})
})
module.exports = {
images: {
deviceSizes: [480, 1024, 1600, 2000],
imageSizes: [16, 32, 48, 64],
path: 'https://example.com/myaccount/',
loader: 'imgix',
},
}
import Document, { Html, Head, Main, NextScript } from 'next/document'
export default class MyDocument extends Document {
render() {
return (
<Html>
<Head crossOrigin="anonymous">
<script
dangerouslySetInnerHTML={{ __html: 'IntersectionObserver = null' }}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
import Link from 'next/link'
const About = () => {
return (
<div>
<Link href="/no-observer">
<a id="link-no-observer">Test No IntersectionObserver</a>
</Link>
</div>
)
}
export default About
import React, { useLayoutEffect } from 'react'
import Image from 'next/image'
const Lazy = () => {
useLayoutEffect(() => {
IntersectionObserver = null //eslint-disable-line
})
return (
<div>
<p id="stubtext">
......
import {
check,
findPort,
killApp,
nextBuild,
nextStart,
waitFor,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'
const appDir = join(__dirname, '../')
let appPort
let app
let browser
describe('Image Component No IntersectionObserver test', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
describe('SSR Lazy Loading Tests', () => {
it('should automatically load images if observer does not exist', async () => {
browser = await webdriver(appPort, '/no-observer')
// Make sure the IntersectionObserver is mocked to null during the test
await check(() => {
return browser.eval('IntersectionObserver')
}, /null/)
expect(
await browser.elementById('lazy-no-observer').getAttribute('src')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000'
)
expect(
await browser.elementById('lazy-no-observer').getAttribute('srcset')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=1024 1x, https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000 2x'
)
})
})
describe('Client-side Lazy Loading Tests', () => {
it('should automatically load images if observer does not exist', async () => {
browser = await webdriver(appPort, '/')
// Make sure the IntersectionObserver is mocked to null during the test
await check(() => {
return browser.eval('IntersectionObserver')
}, /null/)
await browser.waitForElementByCss('#link-no-observer').click()
await waitFor(1000)
expect(
await browser.elementById('lazy-no-observer').getAttribute('src')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000'
)
expect(
await browser.elementById('lazy-no-observer').getAttribute('srcset')
).toBe(
'https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=1024 1x, https://example.com/myaccount/foox.jpg?auto=format&fit=max&w=2000 2x'
)
})
})
})
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