1 | import { useState } from 'react';
|
2 | import useStableMemo from './useStableMemo';
|
3 | import useEffect from './useIsomorphicEffect';
|
4 | import useEventCallback from './useEventCallback';
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | function useIntersectionObserver(element, callbackOrOptions, maybeOptions) {
|
18 | var callback;
|
19 | var options;
|
20 |
|
21 | if (typeof callbackOrOptions === 'function') {
|
22 | callback = callbackOrOptions;
|
23 | options = maybeOptions || {};
|
24 | } else {
|
25 | options = callbackOrOptions || {};
|
26 | }
|
27 |
|
28 | var _options = options,
|
29 | threshold = _options.threshold,
|
30 | root = _options.root,
|
31 | rootMargin = _options.rootMargin;
|
32 |
|
33 | var _useState = useState(null),
|
34 | entries = _useState[0],
|
35 | setEntry = _useState[1];
|
36 |
|
37 | var handler = useEventCallback(callback || setEntry);
|
38 |
|
39 | var observer = useStableMemo(function () {
|
40 | return root !== null && typeof IntersectionObserver !== 'undefined' && new IntersectionObserver(handler, {
|
41 | threshold: threshold,
|
42 | root: root,
|
43 | rootMargin: rootMargin
|
44 | });
|
45 | }, [handler, root, rootMargin, threshold && JSON.stringify(threshold)]);
|
46 | useEffect(function () {
|
47 | if (!element || !observer) return;
|
48 | observer.observe(element);
|
49 | return function () {
|
50 | observer.unobserve(element);
|
51 | };
|
52 | }, [observer, element]);
|
53 | return callback ? undefined : entries || [];
|
54 | }
|
55 |
|
56 | export default useIntersectionObserver; |
\ | No newline at end of file |