-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathuseSticky.ts
More file actions
76 lines (61 loc) · 2.44 KB
/
Copy pathuseSticky.ts
File metadata and controls
76 lines (61 loc) · 2.44 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import {useState} from 'react';
import {useEffectOnce, useLatest} from 'react-use';
import {REFLOW_EVENTS} from 'src/utils/dom';
const CONTAINER_EVENTS = new Set<keyof WindowEventMap>([
'scroll',
'touchstart',
'touchmove',
'touchend',
]);
export function useSticky<T extends HTMLElement>(
elemRef: React.RefObject<T>,
scrollContainerRef?: React.RefObject<HTMLElement>,
) {
const [sticky, setSticky] = useState(false);
const stickyRef = useLatest(sticky);
useEffectOnce(() => {
let rafId: number | null = null;
const scrollContainer = scrollContainerRef?.current ?? null;
const naturalTopFromContainer =
scrollContainer && elemRef.current
? elemRef.current.getBoundingClientRect().top -
scrollContainer.getBoundingClientRect().top -
scrollContainer.clientTop
: null;
const getTarget = (eventName: keyof WindowEventMap): EventTarget =>
CONTAINER_EVENTS.has(eventName) && scrollContainer ? scrollContainer : window;
observe();
for (const eventName of REFLOW_EVENTS) {
getTarget(eventName).addEventListener(eventName, scheduleObserve, true);
}
return () => {
if (rafId !== null) {
cancelAnimationFrame(rafId);
}
for (const eventName of REFLOW_EVENTS) {
getTarget(eventName).removeEventListener(eventName, scheduleObserve, true);
}
};
function scheduleObserve() {
if (rafId !== null) {
cancelAnimationFrame(rafId);
}
rafId = requestAnimationFrame(observe);
}
function observe() {
rafId = null;
if (!elemRef.current) return;
const stickyOffset = parseInt(getComputedStyle(elemRef.current).top, 10);
let stickyActive: boolean;
if (scrollContainer !== null && naturalTopFromContainer !== null) {
stickyActive = scrollContainer.scrollTop >= naturalTopFromContainer - stickyOffset;
} else {
const refPageOffset = elemRef.current.getBoundingClientRect().top;
stickyActive = refPageOffset <= stickyOffset;
}
if (stickyActive && !stickyRef.current) setSticky(true);
else if (!stickyActive && stickyRef.current) setSticky(false);
}
});
return sticky;
}