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 <Image/>'s lazyRoot and other optimizations #37447

Merged
merged 18 commits into from
Jun 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 33 additions & 38 deletions packages/next/client/use-intersection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type Observer = {
elements: Map<Element, ObserveCallback>
}

const hasIntersectionObserver = typeof IntersectionObserver !== 'undefined'
const hasIntersectionObserver = typeof IntersectionObserver === 'function'
SukkaW marked this conversation as resolved.
Show resolved Hide resolved

export function useIntersection<T extends Element>({
rootRef,
Expand All @@ -34,44 +34,42 @@ 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
}

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(
Expand All @@ -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) {
Expand All @@ -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)
}
styfle marked this conversation as resolved.
Show resolved Hide resolved
if (instance) {
return instance
if (instance) {
return instance
}
}

const elements = new Map<Element, ObserveCallback>()
Expand All @@ -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
}
4 changes: 0 additions & 4 deletions test/integration/image-component/basic/pages/lazy.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React from 'react'
import Image from 'next/image'
import Link from 'next/link'

const Lazy = () => {
return (
Expand Down Expand Up @@ -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>
)
}
Expand Down
28 changes: 0 additions & 28 deletions test/integration/image-component/basic/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand All @@ -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'
)
})
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
images: {
deviceSizes: [480, 1024, 1600, 2000],
imageSizes: [16, 32, 48, 64],
path: 'https://example.com/myaccount/',
loader: 'imgix',
},
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
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' }}
/>
styfle marked this conversation as resolved.
Show resolved Hide resolved
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
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
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import React, { useLayoutEffect } from 'react'
import Image from 'next/image'

const Lazy = () => {
useLayoutEffect(() => {
IntersectionObserver = null //eslint-disable-line
})
return (
<div>
<p id="stubtext">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
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'
)
})
})
})