-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
use-intersection.ts
55 lines (46 loc) · 1.56 KB
/
use-intersection.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
"use client";
import { useState, useEffect } from "react";
interface UseIntersectionOptions {
threshold?: number;
prefix?: string;
}
export function useIntersection(
items: { id: string | number }[],
options: UseIntersectionOptions = {}
) {
const [visibleIds, setVisibleIds] = useState<Set<string | number>>(
new Set()
);
useEffect(() => {
const handleIntersection = (entries: IntersectionObserverEntry[]) => {
setVisibleIds((prev) => {
const next = new Set(prev);
for (const entry of entries) {
const id = entry.target.id.replace(
`${options.prefix}-`,
""
);
const parsedId = Number.isNaN(Number(id)) ? id : Number(id);
if (entry.isIntersecting) {
next.add(parsedId);
} else {
next.delete(parsedId);
}
}
return next;
});
};
const observer = new IntersectionObserver(handleIntersection, {
threshold: options.threshold || 0.2,
rootMargin: "-50px 0px",
});
for (const item of items) {
const element = document.getElementById(
`${options.prefix}-${item.id}`
);
if (element) observer.observe(element);
}
return () => observer.disconnect();
}, [items, options.prefix, options.threshold]);
return { visibleIds };
}