phanpy/src/utils/useScroll.js

84 lines
2.5 KiB
JavaScript
Raw Normal View History

import { useEffect, useState } from 'preact/hooks';
export default function useScroll({
2023-01-14 14:42:04 +03:00
scrollableElement,
distanceFromStart = 0,
distanceFromEnd = 0,
scrollThresholdStart = 10,
scrollThresholdEnd = 10,
direction = 'vertical',
} = {}) {
const [scrollDirection, setScrollDirection] = useState(null);
2023-01-14 14:42:04 +03:00
const [reachStart, setReachStart] = useState(false);
const [reachEnd, setReachEnd] = useState(false);
const [nearReachStart, setNearReachStart] = useState(false);
const [nearReachEnd, setNearReachEnd] = useState(false);
const isVertical = direction === 'vertical';
if (!scrollableElement) {
console.warn('Scrollable element is not defined');
scrollableElement = window;
}
useEffect(() => {
2023-01-14 14:42:04 +03:00
let previousScrollStart = isVertical
? scrollableElement.scrollTop
: scrollableElement.scrollLeft;
function onScroll() {
2023-01-14 14:42:04 +03:00
const {
scrollTop,
scrollLeft,
scrollHeight,
scrollWidth,
clientHeight,
clientWidth,
} = scrollableElement;
const scrollStart = isVertical ? scrollTop : scrollLeft;
const scrollDimension = isVertical ? scrollHeight : scrollWidth;
const clientDimension = isVertical ? clientHeight : clientWidth;
const scrollDistance = Math.abs(scrollStart - previousScrollStart);
const distanceFromStartPx =
scrollDimension * Math.min(1, Math.max(0, distanceFromStart));
const distanceFromEndPx =
scrollDimension * Math.min(1, Math.max(0, distanceFromEnd));
2023-01-07 09:45:04 +03:00
if (
scrollDistance >=
2023-01-14 14:42:04 +03:00
(previousScrollStart < scrollStart
? scrollThresholdEnd
: scrollThresholdStart)
2023-01-07 09:45:04 +03:00
) {
2023-01-14 14:42:04 +03:00
setScrollDirection(previousScrollStart < scrollStart ? 'end' : 'start');
previousScrollStart = scrollStart;
}
2023-01-14 14:42:04 +03:00
setReachStart(scrollStart === 0);
setReachEnd(scrollStart + clientDimension >= scrollDimension);
setNearReachStart(scrollStart <= distanceFromStartPx);
setNearReachEnd(
scrollStart + clientDimension >= scrollDimension - distanceFromEndPx,
);
}
scrollableElement.addEventListener('scroll', onScroll, { passive: true });
2023-01-14 14:42:04 +03:00
scrollableElement.dispatchEvent(new Event('scroll'));
return () => scrollableElement.removeEventListener('scroll', onScroll);
2023-01-07 09:45:04 +03:00
}, [
scrollableElement,
2023-01-14 14:42:04 +03:00
distanceFromStart,
distanceFromEnd,
scrollThresholdStart,
scrollThresholdEnd,
2023-01-07 09:45:04 +03:00
]);
2023-01-14 14:42:04 +03:00
return {
scrollDirection,
reachStart,
reachEnd,
nearReachStart,
nearReachEnd,
};
}