-
Notifications
You must be signed in to change notification settings - Fork 95
/
index.ts
173 lines (143 loc) · 4.8 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import {type RefObject, useEffect, useState} from 'react';
const DEFAULT_THRESHOLD = [0];
const DEFAULT_ROOT_MARGIN = '0px';
type IntersectionEntryCallback = (entry: IntersectionObserverEntry) => void;
type ObserverEntry = {
observer: IntersectionObserver;
observe: (target: Element, callback: IntersectionEntryCallback) => void;
unobserve: (target: Element, callback: IntersectionEntryCallback) => void;
};
const observers = new Map<Element | Document, Map<string, ObserverEntry>>();
const getObserverEntry = (options: IntersectionObserverInit): ObserverEntry => {
const root = options.root ?? document;
let rootObservers = observers.get(root);
if (!rootObservers) {
rootObservers = new Map();
observers.set(root, rootObservers);
}
const opt = JSON.stringify([options.rootMargin, options.threshold]);
let observerEntry = rootObservers.get(opt);
if (!observerEntry) {
const callbacks = new Map<Element, Set<IntersectionEntryCallback>>();
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
const cbs = callbacks.get(entry.target);
if (cbs === undefined || cbs.size === 0) {
continue;
}
for (const cb of cbs) {
setTimeout(() => {
cb(entry);
}, 0);
}
}
}, options);
observerEntry = {
observer,
observe(target, callback) {
let cbs = callbacks.get(target);
if (!cbs) {
// If target has no observers yet - register it
cbs = new Set();
callbacks.set(target, cbs);
observer.observe(target);
}
// As Set is duplicate-safe - simply add callback on each call
cbs.add(callback);
},
unobserve(target, callback) {
const cbs = callbacks.get(target);
// Else branch should never occur in case of normal execution
// because callbacks map is hidden in closure - it is impossible to
// simulate situation with non-existent `cbs` Set
if (cbs) {
// Remove current observer
cbs.delete(callback);
if (cbs.size === 0) {
// If no observers left unregister target completely
callbacks.delete(target);
observer.unobserve(target);
// If not tracked elements left - disconnect observer
if (callbacks.size === 0) {
observer.disconnect();
rootObservers.delete(opt);
if (rootObservers.size === 0) {
observers.delete(root);
}
}
}
}
},
};
rootObservers.set(opt, observerEntry);
}
return observerEntry;
};
export type UseIntersectionObserverOptions = {
/**
* An Element or Document object (or its react reference) which is an
* ancestor of the intended target, whose bounding rectangle will be
* considered the viewport. Any part of the target not visible in the visible
* area of the root is not considered visible.
*/
root?: RefObject<Element | Document> | Element | Document | null;
/**
* A string which specifies a set of offsets to add to the root's bounding_box
* when calculating intersections, effectively shrinking or growing the root
* for calculation purposes. The syntax is approximately the same as that for
* the CSS margin property; The default is `0px`.
*/
rootMargin?: string;
/**
* Array of numbers between 0.0 and 1.0, specifying a ratio of intersection
* area to total bounding box area for the observed target. A value of 0.0
* means that even a single visible pixel counts as the target being visible.
* 1.0 means that the entire target element is visible.
* The default is a threshold of `[0]`.
*/
threshold?: number[];
};
/**
* Tracks intersection of a target element with an ancestor element or with a
* top-level document's viewport.
*
* @param target React reference or Element to track.
* @param options Like `IntersectionObserver` options but `root` can also be
* react reference
*/
export function useIntersectionObserver<T extends Element>(
target: RefObject<T> | T | null,
{
threshold = DEFAULT_THRESHOLD,
root: r,
rootMargin = DEFAULT_ROOT_MARGIN,
}: UseIntersectionObserverOptions = {},
): IntersectionObserverEntry | undefined {
const [state, setState] = useState<IntersectionObserverEntry>();
useEffect(() => {
const tgt = target && 'current' in target ? target.current : target;
if (!tgt) {
return;
}
let subscribed = true;
const observerEntry = getObserverEntry({
root: r && 'current' in r ? r.current : r,
rootMargin,
threshold,
});
const handler: IntersectionEntryCallback = (entry) => {
// It is reinsurance for the highly asynchronous invocations, almost
// impossible to achieve in tests, thus excluding from LOC
if (subscribed) {
setState(entry);
}
};
observerEntry.observe(tgt, handler);
return () => {
subscribed = false;
observerEntry.unobserve(tgt, handler);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [target, r, rootMargin, ...threshold]);
return state;
}