index.mjs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { resolveElements } from 'motion-dom';
  2. const thresholds = {
  3. some: 0,
  4. all: 1,
  5. };
  6. function inView(elementOrSelector, onStart, { root, margin: rootMargin, amount = "some" } = {}) {
  7. const elements = resolveElements(elementOrSelector);
  8. const activeIntersections = new WeakMap();
  9. const onIntersectionChange = (entries) => {
  10. entries.forEach((entry) => {
  11. const onEnd = activeIntersections.get(entry.target);
  12. /**
  13. * If there's no change to the intersection, we don't need to
  14. * do anything here.
  15. */
  16. if (entry.isIntersecting === Boolean(onEnd))
  17. return;
  18. if (entry.isIntersecting) {
  19. const newOnEnd = onStart(entry.target, entry);
  20. if (typeof newOnEnd === "function") {
  21. activeIntersections.set(entry.target, newOnEnd);
  22. }
  23. else {
  24. observer.unobserve(entry.target);
  25. }
  26. }
  27. else if (typeof onEnd === "function") {
  28. onEnd(entry);
  29. activeIntersections.delete(entry.target);
  30. }
  31. });
  32. };
  33. const observer = new IntersectionObserver(onIntersectionChange, {
  34. root,
  35. rootMargin,
  36. threshold: typeof amount === "number" ? amount : thresholds[amount],
  37. });
  38. elements.forEach((element) => observer.observe(element));
  39. return () => observer.disconnect();
  40. }
  41. export { inView };