Skip to content
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"@babel/cli": "^7.12.10",
"@babel/core": "^7.12.10",
"@babel/preset-typescript": "^7.12.7",
"@testing-library/react-hooks": "^7.0.0",
"@types/enzyme": "^3.10.8",
"@types/jest": "^26.0.19",
"@types/lodash": "^4.14.167",
Expand Down
21 changes: 16 additions & 5 deletions src/useIntersectionObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@ import useEventCallback from './useEventCallback'
* a DOM Element that returns it's entries as they arrive.
*
* @param element The DOM element to observe
* @param init IntersectionObserver options
* @param init IntersectionObserver options with a notable change,
* unlike a plain IntersectionObserver `root: null` means "not provided YET",
* and the hook will wait until it receives a non-null value to set up the observer.
* This change allows for easier syncing of element and root values in a React
* context.
*/
function useIntersectionObserver<TElement extends Element>(
element: TElement | null | undefined,
options: IntersectionObserverInit,
options?: IntersectionObserverInit,
): IntersectionObserverEntry[]
/**
* Setup an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) on
Expand All @@ -22,16 +26,21 @@ function useIntersectionObserver<TElement extends Element>(
*
* @param element The DOM element to observe
* @param callback A listener for intersection updates.
* @param init IntersectionObserver options
* @param init IntersectionObserver options with a notable change,
* unlike a plain IntersectionObserver `root: null` means "not provided YET",
* and the hook will wait until it receives a non-null value to set up the observer.
* This change allows for easier syncing of element and root values in a React
* context.
*
*/
function useIntersectionObserver<TElement extends Element>(
element: TElement | null | undefined,
callback: IntersectionObserverCallback,
options: IntersectionObserverInit,
options?: IntersectionObserverInit,
): void
function useIntersectionObserver<TElement extends Element>(
element: TElement | null | undefined,
callbackOrOptions: IntersectionObserverCallback | IntersectionObserverInit,
callbackOrOptions?: IntersectionObserverCallback | IntersectionObserverInit,
maybeOptions?: IntersectionObserverInit,
): void | IntersectionObserverEntry[] {
let callback: IntersectionObserverCallback | undefined
Expand All @@ -47,8 +56,10 @@ function useIntersectionObserver<TElement extends Element>(

const handler = useEventCallback(callback || setEntry)

// We wait for element to exist before constructing
const observer = useStableMemo(
() =>
root !== null &&
typeof IntersectionObserver !== 'undefined' &&
new IntersectionObserver(handler, {
threshold,
Expand Down
94 changes: 94 additions & 0 deletions test/useIntersectionObserver.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import useIntersectionObserver from '../src/useIntersectionObserver'
import useCallbackRef from '../src/useCallbackRef'
import React from 'react'
import { renderHook, act } from '@testing-library/react-hooks'

describe('useIntersectionObserver', () => {
let observers: any[] = []
beforeEach(() => {
;(window as any).IntersectionObserver = class IntersectionObserverMock {
observe: jest.Mock<any, any>
unobserve: jest.Mock<any, any>
args: [IntersectionObserverCallback, IntersectionObserverEntryInit]
constructor(handler: any, init: any) {
this.args = [handler, init]
this.observe = jest.fn()
this.unobserve = jest.fn()
observers.push(this)
}
}
})

afterEach(() => {
observers = []
})

it('should observe element', async () => {
const element = document.createElement('span')

const { result } = renderHook(() => useIntersectionObserver(element))
const entry = {}
expect(result.current).toEqual([])

act(() => {
observers[0].args[0]([entry])
})

expect(result.current[0]).toStrictEqual(entry)
})

it('should wait for element', async () => {
const element = document.createElement('span')

const { result, rerender, unmount } = renderHook(
({ element }) => useIntersectionObserver(element),
{ initialProps: { element: null as any } },
)

expect(result.current).toEqual([])

expect(observers[0].observe).not.toBeCalled()

rerender({ element })

expect(observers[0].observe).toBeCalledTimes(1)

unmount()

expect(observers[0].unobserve).toBeCalledTimes(1)
})

it('should wait for root to set up observer', async () => {
const root = document.createElement('div')
const element = document.createElement('span')

const { result, rerender } = renderHook(
(root: any) => useIntersectionObserver(element, { root }),
{ initialProps: null },
)

expect(observers).toHaveLength(0)

rerender(root)

expect(observers).toHaveLength(1)
expect(observers[0].observe).toBeCalledTimes(1)
})

it('should accept a callback', async () => {
const spy = jest.fn()
const element = document.createElement('span')

const { result } = renderHook(() => useIntersectionObserver(element, spy))

expect(result.current).toEqual(undefined)

const entry = {}
act(() => {
observers[0].args[0]([entry, observers[0]])
})

expect(spy).toBeCalledTimes(1)
expect(spy).toHaveBeenLastCalledWith([entry, observers[0]])
})
})
53 changes: 53 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1093,6 +1093,13 @@
core-js-pure "^3.0.0"
regenerator-runtime "^0.13.4"

"@babel/runtime@^7.12.5":
version "7.14.6"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.14.6.tgz#535203bc0892efc7dec60bdc27b2ecf6e409062d"
integrity sha512-/PCB2uJ7oM44tz8YhC4Z/6PeOKXp4K588f+5M3clr1M4zbqztlo0XEfJ2LEzj/FgwfgGcIdl8n7YYjTCI0BYwg==
dependencies:
regenerator-runtime "^0.13.4"

"@babel/runtime@^7.5.5", "@babel/runtime@^7.8.4":
version "7.13.9"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.13.9.tgz#97dbe2116e2630c489f22e0656decd60aaa1fcee"
Expand Down Expand Up @@ -1472,6 +1479,17 @@
dependencies:
"@sinonjs/commons" "^1.7.0"

"@testing-library/react-hooks@^7.0.0":
version "7.0.0"
resolved "https://registry.yarnpkg.com/@testing-library/react-hooks/-/react-hooks-7.0.0.tgz#dd6d37a7e018f147a3b9153137f10e013be8472b"
integrity sha512-WFBGH8DWdIGGBHt6PBtQPe2v4Kbj9vQ1sQ9qLBTmwn1PNggngint4MTE/IiWCYhPbyTW3oc/7X62DObMn/AjQQ==
dependencies:
"@babel/runtime" "^7.12.5"
"@types/react" ">=16.9.0"
"@types/react-dom" ">=16.9.0"
"@types/react-test-renderer" ">=16.9.0"
react-error-boundary "^3.1.0"

"@tootallnate/once@1":
version "1.1.2"
resolved "https://registry.yarnpkg.com/@tootallnate/once/-/once-1.1.2.tgz#ccb91445360179a04e7fe6aff78c00ffc1eeaf82"
Expand Down Expand Up @@ -1637,6 +1655,20 @@
resolved "https://registry.yarnpkg.com/@types/q/-/q-1.5.4.tgz#15925414e0ad2cd765bfef58842f7e26a7accb24"
integrity sha512-1HcDas8SEj4z1Wc696tH56G8OlRaH/sqZOynNNB+HF0WOeXPaxTtbYzJY2oEfiUxjSKjhCKr+MvR7dCHcEelug==

"@types/react-dom@>=16.9.0":
version "17.0.7"
resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-17.0.7.tgz#b8ee15ead9e5d6c2c858b44949fdf2ebe5212232"
integrity sha512-Wd5xvZRlccOrCTej8jZkoFZuZRKHzanDDv1xglI33oBNFMWrqOSzrvWFw7ngSiZjrpJAzPKFtX7JvuXpkNmQHA==
dependencies:
"@types/react" "*"

"@types/react-test-renderer@>=16.9.0":
version "17.0.1"
resolved "https://registry.yarnpkg.com/@types/react-test-renderer/-/react-test-renderer-17.0.1.tgz#3120f7d1c157fba9df0118dae20cb0297ee0e06b"
integrity sha512-3Fi2O6Zzq/f3QR9dRnlnHso9bMl7weKCviFmfF6B4LS1Uat6Hkm15k0ZAQuDz+UBq6B3+g+NM6IT2nr5QgPzCw==
dependencies:
"@types/react" "*"

"@types/react@*", "@types/react@^17.0.0":
version "17.0.2"
resolved "https://registry.yarnpkg.com/@types/react/-/react-17.0.2.tgz#3de24c4efef902dd9795a49c75f760cbe4f7a5a8"
Expand All @@ -1645,6 +1677,20 @@
"@types/prop-types" "*"
csstype "^3.0.2"

"@types/react@>=16.9.0":
version "17.0.11"
resolved "https://registry.yarnpkg.com/@types/react/-/react-17.0.11.tgz#67fcd0ddbf5a0b083a0f94e926c7d63f3b836451"
integrity sha512-yFRQbD+whVonItSk7ZzP/L+gPTJVBkL/7shLEF+i9GC/1cV3JmUxEQz6+9ylhUpWSDuqo1N9qEvqS6vTj4USUA==
dependencies:
"@types/prop-types" "*"
"@types/scheduler" "*"
csstype "^3.0.2"

"@types/scheduler@*":
version "0.16.1"
resolved "https://registry.yarnpkg.com/@types/scheduler/-/scheduler-0.16.1.tgz#18845205e86ff0038517aab7a18a62a6b9f71275"
integrity sha512-EaCxbanVeyxDRTQBkdLb3Bvl/HK7PBK6UJjsSixB0iHKoWxE5uu2Q/DgtpOhPIojN0Zl1whvOd7PoHs2P0s5eA==

"@types/schema-utils@^2.4.0":
version "2.4.0"
resolved "https://registry.yarnpkg.com/@types/schema-utils/-/schema-utils-2.4.0.tgz#9983012045d541dcee053e685a27c9c87c840fcd"
Expand Down Expand Up @@ -7915,6 +7961,13 @@ react-dom@^16.13.0:
prop-types "^15.6.2"
scheduler "^0.19.1"

react-error-boundary@^3.1.0:
version "3.1.3"
resolved "https://registry.yarnpkg.com/react-error-boundary/-/react-error-boundary-3.1.3.tgz#276bfa05de8ac17b863587c9e0647522c25e2a0b"
integrity sha512-A+F9HHy9fvt9t8SNDlonq01prnU8AmkjvGKV4kk8seB9kU3xMEO8J/PQlLVmoOIDODl5U2kufSBs4vrWIqhsAA==
dependencies:
"@babel/runtime" "^7.12.5"

react-error-overlay@^6.0.9:
version "6.0.9"
resolved "https://registry.yarnpkg.com/react-error-overlay/-/react-error-overlay-6.0.9.tgz#3c743010c9359608c375ecd6bc76f35d93995b0a"
Expand Down