31 lines
841 B
JavaScript
31 lines
841 B
JavaScript
/*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
*/
|
|
// Stolen from https://svelte.dev/repl/c6a402704224403f96a3db56c2f48dfc?version=3.55.0
|
|
let intersectionObserver;
|
|
|
|
function ensureIntersectionObserver() {
|
|
if (intersectionObserver) return;
|
|
|
|
intersectionObserver = new IntersectionObserver((entries) => {
|
|
entries.forEach((entry) => {
|
|
const eventName = entry.isIntersecting ? 'enterViewport' : 'exitViewport';
|
|
entry.target.dispatchEvent(new CustomEvent(eventName));
|
|
});
|
|
});
|
|
}
|
|
|
|
export default function viewport(element) {
|
|
ensureIntersectionObserver();
|
|
|
|
intersectionObserver.observe(element);
|
|
|
|
return {
|
|
destroy() {
|
|
intersectionObserver.unobserve(element);
|
|
}
|
|
};
|
|
}
|