Update useScroll to check distance in threshold instead of pixels

This commit is contained in:
Lim Chee Aun 2023-01-05 15:29:11 +08:00
parent 599d81f924
commit de45a0f9d5
2 changed files with 11 additions and 6 deletions

View file

@ -165,8 +165,8 @@ function Home({ hidden }) {
const { scrollDirection, reachTop, nearReachTop, nearReachBottom } =
useScroll({
scrollableElement: scrollableRef.current,
distanceFromTop: window.innerHeight / 2,
distanceFromBottom: window.innerHeight,
distanceFromTop: 0.1,
distanceFromBottom: 0.15,
});
useEffect(() => {
@ -247,8 +247,9 @@ function Home({ hidden }) {
</div>
</header>
{snapStates.homeNew.length > 0 &&
((scrollDirection === 'up' && !nearReachTop && !nearReachBottom) ||
reachTop) && (
scrollDirection === 'up' &&
!nearReachTop &&
!nearReachBottom && (
<button
class="updates-button"
type="button"

View file

@ -17,6 +17,10 @@ export default function useScroll({
function onScroll() {
const { scrollTop, scrollHeight, clientHeight } = scrollableElement;
const scrollDistance = Math.abs(scrollTop - previousScrollTop);
const distanceFromTopPx =
scrollHeight * Math.min(1, Math.max(0, distanceFromTop));
const distanceFromBottomPx =
scrollHeight * Math.min(1, Math.max(0, distanceFromBottom));
if (scrollDistance >= scrollThreshold) {
setScrollDirection(previousScrollTop < scrollTop ? 'down' : 'up');
@ -24,9 +28,9 @@ export default function useScroll({
}
setReachTop(scrollTop === 0);
setNearReachTop(scrollTop <= distanceFromTop);
setNearReachTop(scrollTop <= distanceFromTopPx);
setNearReachBottom(
scrollTop + clientHeight >= scrollHeight - distanceFromBottom,
scrollTop + clientHeight >= scrollHeight - distanceFromBottomPx,
);
}