Unverified Commit 7452c0bf authored by 11koukou's avatar 11koukou Committed by GitHub

Add `lazyRoot` optional property to `next/image` component (#33290)

* Added 'rootEl' oprional property to next/Image component resembling 'root' option of the Intersection Observer API

* changed 'rootEl' to 'lazyBoundary' and its type as well

* added test, fixed initial root detection

* Update test/integration/image-component/default/test/index.test.js
Co-authored-by: 's avatarSteven <steven@ceriously.com>

* prop names changed

* added 'lazyroot' prop to the documentation

* removed unused import

* Apply suggestions from code review

* Update docs with lazyRoot added in 12.0.9
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent 9dd0399d
...@@ -16,6 +16,7 @@ description: Enable Image Optimization with the built-in Image component. ...@@ -16,6 +16,7 @@ description: Enable Image Optimization with the built-in Image component.
| Version | Changes | | Version | Changes |
| --------- | ------------------------------------------------------------------------------------------------- | | --------- | ------------------------------------------------------------------------------------------------- |
| `v12.0.9` | `lazyRoot` prop added |
| `v12.0.0` | `formats` configuration added.<br/>AVIF support added.<br/>Wrapper `<div>` changed to `<span>`. | | `v12.0.0` | `formats` configuration added.<br/>AVIF support added.<br/>Wrapper `<div>` changed to `<span>`. |
| `v11.1.0` | `onLoadingComplete` and `lazyBoundary` props added. | | `v11.1.0` | `onLoadingComplete` and `lazyBoundary` props added. |
| `v11.0.0` | `src` prop support for static import.<br/>`placeholder` prop added.<br/>`blurDataURL` prop added. | | `v11.0.0` | `src` prop support for static import.<br/>`placeholder` prop added.<br/>`blurDataURL` prop added. |
...@@ -221,6 +222,12 @@ A string (with similar syntax to the margin property) that acts as the bounding ...@@ -221,6 +222,12 @@ A string (with similar syntax to the margin property) that acts as the bounding
[Learn more](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/rootMargin) [Learn more](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/rootMargin)
### lazyRoot
A React [Ref](https://reactjs.org/docs/refs-and-the-dom.html) pointing to the Element which the [lazyBoundary](#lazyBoundary) calculates for the Intersection detection. Defaults to `null`, referring to the document viewport.
[Learn more](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/root)
### unoptimized ### unoptimized
When true, the source image will be served as-is instead of changing quality, When true, the source image will be served as-is instead of changing quality,
......
...@@ -100,6 +100,7 @@ export type ImageProps = Omit< ...@@ -100,6 +100,7 @@ export type ImageProps = Omit<
quality?: number | string quality?: number | string
priority?: boolean priority?: boolean
loading?: LoadingValue loading?: LoadingValue
lazyRoot?: React.RefObject<HTMLElement> | null
lazyBoundary?: string lazyBoundary?: string
placeholder?: PlaceholderValue placeholder?: PlaceholderValue
blurDataURL?: string blurDataURL?: string
...@@ -319,6 +320,7 @@ export default function Image({ ...@@ -319,6 +320,7 @@ export default function Image({
unoptimized = false, unoptimized = false,
priority = false, priority = false,
loading, loading,
lazyRoot = null,
lazyBoundary = '200px', lazyBoundary = '200px',
className, className,
quality, quality,
...@@ -510,6 +512,7 @@ export default function Image({ ...@@ -510,6 +512,7 @@ export default function Image({
} }
const [setIntersection, isIntersected] = useIntersection<HTMLImageElement>({ const [setIntersection, isIntersected] = useIntersection<HTMLImageElement>({
rootRef: lazyRoot,
rootMargin: lazyBoundary, rootMargin: lazyBoundary,
disabled: !isLazy, disabled: !isLazy,
}) })
......
...@@ -4,8 +4,14 @@ import { ...@@ -4,8 +4,14 @@ import {
cancelIdleCallback, cancelIdleCallback,
} from './request-idle-callback' } from './request-idle-callback'
type UseIntersectionObserverInit = Pick<IntersectionObserverInit, 'rootMargin'> type UseIntersectionObserverInit = Pick<
type UseIntersection = { disabled?: boolean } & UseIntersectionObserverInit IntersectionObserverInit,
'rootMargin' | 'root'
>
type UseIntersection = { disabled?: boolean } & UseIntersectionObserverInit & {
rootRef?: React.RefObject<HTMLElement> | null
}
type ObserveCallback = (isVisible: boolean) => void type ObserveCallback = (isVisible: boolean) => void
type Observer = { type Observer = {
id: string id: string
...@@ -16,6 +22,7 @@ type Observer = { ...@@ -16,6 +22,7 @@ type Observer = {
const hasIntersectionObserver = typeof IntersectionObserver !== 'undefined' const hasIntersectionObserver = typeof IntersectionObserver !== 'undefined'
export function useIntersection<T extends Element>({ export function useIntersection<T extends Element>({
rootRef,
rootMargin, rootMargin,
disabled, disabled,
}: UseIntersection): [(element: T | null) => void, boolean] { }: UseIntersection): [(element: T | null) => void, boolean] {
...@@ -23,7 +30,7 @@ export function useIntersection<T extends Element>({ ...@@ -23,7 +30,7 @@ export function useIntersection<T extends Element>({
const unobserve = useRef<Function>() const unobserve = useRef<Function>()
const [visible, setVisible] = useState(false) const [visible, setVisible] = useState(false)
const [root, setRoot] = useState(rootRef ? rootRef.current : null)
const setRef = useCallback( const setRef = useCallback(
(el: T | null) => { (el: T | null) => {
if (unobserve.current) { if (unobserve.current) {
...@@ -37,11 +44,11 @@ export function useIntersection<T extends Element>({ ...@@ -37,11 +44,11 @@ export function useIntersection<T extends Element>({
unobserve.current = observe( unobserve.current = observe(
el, el,
(isVisible) => isVisible && setVisible(isVisible), (isVisible) => isVisible && setVisible(isVisible),
{ rootMargin } { root, rootMargin }
) )
} }
}, },
[isDisabled, rootMargin, visible] [isDisabled, root, rootMargin, visible]
) )
useEffect(() => { useEffect(() => {
...@@ -53,6 +60,9 @@ export function useIntersection<T extends Element>({ ...@@ -53,6 +60,9 @@ export function useIntersection<T extends Element>({
} }
}, [visible]) }, [visible])
useEffect(() => {
if (rootRef) setRoot(rootRef.current)
}, [rootRef])
return [setRef, visible] return [setRef, visible]
} }
......
import React, { useRef } from 'react'
import Image from 'next/image'
const Page = () => {
const myRef = useRef(null)
return (
<>
<div
ref={myRef}
style={{
width: '100%',
height: '400px',
position: 'relative',
overflowY: 'scroll',
}}
>
<div style={{ width: '400px', height: '600px' }}>hello</div>
<div style={{ width: '400px', position: 'relative', height: '600px' }}>
<Image
id="myImage"
src="/test.jpg"
width="400"
height="400"
lazyBoundary="1800px"
/>
</div>
</div>
</>
)
}
export default Page
import React, { useRef } from 'react'
import Image from 'next/image'
const Page = () => {
const myRef = useRef(null)
return (
<>
<div
ref={myRef}
style={{
width: '100%',
height: '400px',
position: 'relative',
overflowY: 'scroll',
}}
>
<div style={{ width: '400px', height: '600px' }}>hello</div>
<div style={{ width: '400px', position: 'relative', height: '600px' }}>
<Image
lazyRoot={myRef}
id="myImage"
src="/test.jpg"
width="400"
height="400"
lazyBoundary="1800px"
/>
</div>
</div>
</>
)
}
export default Page
...@@ -1008,6 +1008,37 @@ function runTests(mode) { ...@@ -1008,6 +1008,37 @@ function runTests(mode) {
} }
} }
}) })
it('should load the image when the lazyRoot prop is used', async () => {
let browser
try {
//trying on '/lazy-noref' it fails
browser = await webdriver(appPort, '/lazy-withref')
await check(async () => {
const result = await browser.eval(
`document.getElementById('myImage').naturalWidth`
)
if (result < 400) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
expect(
await hasImageMatchingUrl(
browser,
`http://localhost:${appPort}/_next/image?url=%2Ftest.jpg&w=828&q=75`
)
).toBe(true)
} finally {
if (browser) {
await browser.close()
}
}
})
} }
describe('Image Component Tests', () => { describe('Image Component 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