phanpy/src/utils/useScroll.js

92 lines
2.7 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 = 1, // ratio of clientHeight/clientWidth
distanceFromEnd = 1, // ratio of clientHeight/clientWidth
2023-01-14 14:42:04 +03:00
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) {
// Better be explicit instead of auto-assign to window
return {};
2023-01-14 14:42:04 +03:00
}
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);
2023-02-03 16:08:08 +03:00
const distanceFromStartPx = Math.min(
clientDimension * distanceFromStart,
scrollDimension,
);
const distanceFromEndPx = Math.min(
clientDimension * distanceFromEnd,
scrollDimension,
);
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;
}
setReachStart(scrollStart <= 0);
2023-01-14 14:42:04 +03:00
setReachEnd(scrollStart + clientDimension >= scrollDimension);
setNearReachStart(scrollStart <= distanceFromStartPx);
setNearReachEnd(
scrollStart + clientDimension >= scrollDimension - distanceFromEndPx,
);
}
scrollableElement.addEventListener('scroll', onScroll, { passive: true });
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,
init: () => {
if (scrollableElement) {
scrollableElement.dispatchEvent(new Event('scroll'));
}
},
2023-01-14 14:42:04 +03:00
};
}