Some checks failed
Build & Deploy / 🔍 Prepare (push) Successful in 20s
Build & Deploy / 🧪 QA (push) Failing after 34s
Build & Deploy / 🏗️ Build (push) Has started running
Build & Deploy / 🚀 Deploy (push) Has been cancelled
Build & Deploy / 🧪 Smoke Test (push) Has been cancelled
Build & Deploy / ⚡ Lighthouse (push) Has been cancelled
Build & Deploy / 🔔 Notify (push) Has been cancelled
44 lines
1.5 KiB
Plaintext
44 lines
1.5 KiB
Plaintext
import { resolveElements } from 'motion-dom';
|
|
|
|
const thresholds = {
|
|
some: 0,
|
|
all: 1,
|
|
};
|
|
function inView(elementOrSelector, onStart, { root, margin: rootMargin, amount = "some" } = {}) {
|
|
const elements = resolveElements(elementOrSelector);
|
|
const activeIntersections = new WeakMap();
|
|
const onIntersectionChange = (entries) => {
|
|
entries.forEach((entry) => {
|
|
const onEnd = activeIntersections.get(entry.target);
|
|
/**
|
|
* If there's no change to the intersection, we don't need to
|
|
* do anything here.
|
|
*/
|
|
if (entry.isIntersecting === Boolean(onEnd))
|
|
return;
|
|
if (entry.isIntersecting) {
|
|
const newOnEnd = onStart(entry);
|
|
if (typeof newOnEnd === "function") {
|
|
activeIntersections.set(entry.target, newOnEnd);
|
|
}
|
|
else {
|
|
observer.unobserve(entry.target);
|
|
}
|
|
}
|
|
else if (typeof onEnd === "function") {
|
|
onEnd(entry);
|
|
activeIntersections.delete(entry.target);
|
|
}
|
|
});
|
|
};
|
|
const observer = new IntersectionObserver(onIntersectionChange, {
|
|
root,
|
|
rootMargin,
|
|
threshold: typeof amount === "number" ? amount : thresholds[amount],
|
|
});
|
|
elements.forEach((element) => observer.observe(element));
|
|
return () => observer.disconnect();
|
|
}
|
|
|
|
export { inView };
|