-
Notifications
You must be signed in to change notification settings - Fork 185
/
observe.ts
171 lines (150 loc) · 5.34 KB
/
observe.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
import type { ObserverInstanceCallback } from "./index";
const observerMap = new Map<
string,
{
id: string;
observer: IntersectionObserver;
elements: Map<Element, Array<ObserverInstanceCallback>>;
}
>();
const RootIds: WeakMap<Element | Document, string> = new WeakMap();
let rootId = 0;
let unsupportedValue: boolean | undefined = undefined;
/**
* What should be the default behavior if the IntersectionObserver is unsupported?
* Ideally the polyfill has been loaded, you can have the following happen:
* - `undefined`: Throw an error
* - `true` or `false`: Set the `inView` value to this regardless of intersection state
* **/
export function defaultFallbackInView(inView: boolean | undefined) {
unsupportedValue = inView;
}
/**
* Generate a unique ID for the root element
* @param root
*/
function getRootId(root: IntersectionObserverInit["root"]) {
if (!root) return "0";
if (RootIds.has(root)) return RootIds.get(root);
rootId += 1;
RootIds.set(root, rootId.toString());
return RootIds.get(root);
}
/**
* Convert the options to a string Id, based on the values.
* Ensures we can reuse the same observer when observing elements with the same options.
* @param options
*/
export function optionsToId(options: IntersectionObserverInit) {
return Object.keys(options)
.sort()
.filter(
(key) => options[key as keyof IntersectionObserverInit] !== undefined,
)
.map((key) => {
return `${key}_${
key === "root"
? getRootId(options.root)
: options[key as keyof IntersectionObserverInit]
}`;
})
.toString();
}
function createObserver(options: IntersectionObserverInit) {
// Create a unique ID for this observer instance, based on the root, root margin and threshold.
const id = optionsToId(options);
let instance = observerMap.get(id);
if (!instance) {
// Create a map of elements this observer is going to observe. Each element has a list of callbacks that should be triggered, once it comes into view.
const elements = new Map<Element, Array<ObserverInstanceCallback>>();
// biome-ignore lint/style/useConst: It's fine to use let here, as we are going to assign it later
let thresholds: number[] | readonly number[];
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
// While it would be nice if you could just look at isIntersecting to determine if the component is inside the viewport, browsers can't agree on how to use it.
// -Firefox ignores `threshold` when considering `isIntersecting`, so it will never be false again if `threshold` is > 0
const inView =
entry.isIntersecting &&
thresholds.some((threshold) => entry.intersectionRatio >= threshold);
// @ts-ignore support IntersectionObserver v2
if (options.trackVisibility && typeof entry.isVisible === "undefined") {
// The browser doesn't support Intersection Observer v2, falling back to v1 behavior.
// @ts-ignore
entry.isVisible = inView;
}
elements.get(entry.target)?.forEach((callback) => {
callback(inView, entry);
});
});
}, options);
// Ensure we have a valid thresholds array. If not, use the threshold from the options
thresholds =
observer.thresholds ||
(Array.isArray(options.threshold)
? options.threshold
: [options.threshold || 0]);
instance = {
id,
observer,
elements,
};
observerMap.set(id, instance);
}
return instance;
}
/**
* @param element - DOM Element to observe
* @param callback - Callback function to trigger when intersection status changes
* @param options - Intersection Observer options
* @param fallbackInView - Fallback inView value.
* @return Function - Cleanup function that should be triggered to unregister the observer
*/
export function observe(
element: Element,
callback: ObserverInstanceCallback,
options: IntersectionObserverInit = {},
fallbackInView = unsupportedValue,
) {
if (
typeof window.IntersectionObserver === "undefined" &&
fallbackInView !== undefined
) {
const bounds = element.getBoundingClientRect();
callback(fallbackInView, {
isIntersecting: fallbackInView,
target: element,
intersectionRatio:
typeof options.threshold === "number" ? options.threshold : 0,
time: 0,
boundingClientRect: bounds,
intersectionRect: bounds,
rootBounds: bounds,
});
return () => {
// Nothing to cleanup
};
}
// An observer with the same options can be reused, so lets use this fact
const { id, observer, elements } = createObserver(options);
// Register the callback listener for this element
const callbacks = elements.get(element) || [];
if (!elements.has(element)) {
elements.set(element, callbacks);
}
callbacks.push(callback);
observer.observe(element);
return function unobserve() {
// Remove the callback from the callback list
callbacks.splice(callbacks.indexOf(callback), 1);
if (callbacks.length === 0) {
// No more callback exists for element, so destroy it
elements.delete(element);
observer.unobserve(element);
}
if (elements.size === 0) {
// No more elements are being observer by this instance, so destroy it
observer.disconnect();
observerMap.delete(id);
}
};
}