@rtdui/hooks
Version:
React hooks library base on @mantine/hooks
54 lines (51 loc) • 1.42 kB
JavaScript
'use client';
import { useRef, useState, useEffect } from 'react';
function defaultTrigger(store, options) {
const {
disableHysteresis = true,
threshold = 0,
target,
direction = "vertical"
} = options;
const previous = store.current;
if (target) {
if (direction === "vertical") {
store.current = target === window ? target.scrollY : target.scrollTop;
} else {
store.current = target === window ? target.scrollX : target.scrollLeft;
}
}
if (!disableHysteresis && previous !== void 0) {
if (store.current < previous) {
return false;
}
}
return store.current > threshold;
}
function useScrollTrigger(options) {
const { getTrigger = defaultTrigger, target, disabled, ...other } = options;
const store = useRef();
const [trigger, setTrigger] = useState(false);
const handleScroll = () => {
setTrigger(getTrigger(store, { target, ...other }));
};
const mounted = useRef(false);
useEffect(() => {
if (mounted.current && target && !disabled) {
handleScroll();
target.addEventListener("scroll", handleScroll, {
passive: true
});
} else {
mounted.current = true;
}
return () => {
if (target) {
target.removeEventListener("scroll", handleScroll);
}
};
}, [target, disabled]);
return trigger;
}
export { useScrollTrigger };
//# sourceMappingURL=useScrollTrigger.mjs.map