react-transition-preset
Version:
Lightweight, zero-dependency transition component for React with common preset transition
44 lines (42 loc) • 1.4 kB
JavaScript
// src/viewport/index.ts
var thresholds = {
some: 0,
all: 1
};
function resolveElements(elements) {
if (typeof elements === "string") {
elements = document.querySelectorAll(elements);
} else if (elements instanceof Element) {
elements = [elements];
}
return Array.from(elements || []);
}
function inView(elementOrSelector, onStart, { root, margin: rootMargin, amount = "some" } = {}) {
const elements = resolveElements(elementOrSelector);
const activeIntersections = /* @__PURE__ */ new WeakMap();
const onIntersectionChange = (entries) => {
entries.forEach((entry) => {
const onEnd = activeIntersections.get(entry.target);
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 (onEnd) {
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, resolveElements };