1 | 'use client';
|
2 |
|
3 | import * as React from 'react';
|
4 | function defaultTrigger(store, options) {
|
5 | const {
|
6 | disableHysteresis = false,
|
7 | threshold = 100,
|
8 | target
|
9 | } = options;
|
10 | const previous = store.current;
|
11 | if (target) {
|
12 |
|
13 | store.current = target.pageYOffset !== undefined ? target.pageYOffset : target.scrollTop;
|
14 | }
|
15 | if (!disableHysteresis && previous !== undefined) {
|
16 | if (store.current < previous) {
|
17 | return false;
|
18 | }
|
19 | }
|
20 | return store.current > threshold;
|
21 | }
|
22 | const defaultTarget = typeof window !== 'undefined' ? window : null;
|
23 | export default function useScrollTrigger(options = {}) {
|
24 | const {
|
25 | getTrigger = defaultTrigger,
|
26 | target = defaultTarget,
|
27 | ...other
|
28 | } = options;
|
29 | const store = React.useRef();
|
30 | const [trigger, setTrigger] = React.useState(() => getTrigger(store, other));
|
31 | React.useEffect(() => {
|
32 | const handleScroll = () => {
|
33 | setTrigger(getTrigger(store, {
|
34 | target,
|
35 | ...other
|
36 | }));
|
37 | };
|
38 | handleScroll();
|
39 | target.addEventListener('scroll', handleScroll, {
|
40 | passive: true
|
41 | });
|
42 | return () => {
|
43 | target.removeEventListener('scroll', handleScroll, {
|
44 | passive: true
|
45 | });
|
46 | };
|
47 |
|
48 |
|
49 |
|
50 | }, [target, getTrigger, JSON.stringify(other)]);
|
51 | return trigger;
|
52 | } |
\ | No newline at end of file |