|
| 1 | +import React from 'react'; |
| 2 | + |
| 3 | +export enum ScrollDirection { |
| 4 | + UP = 'up', |
| 5 | + DOWN = 'down', |
| 6 | +} |
| 7 | + |
| 8 | +interface UseStickyNavProps { |
| 9 | + initialDirection?: ScrollDirection; |
| 10 | + thresholdPixels?: number; |
| 11 | + stickyRef: React.RefObject<HTMLElement>; |
| 12 | +} |
| 13 | + |
| 14 | +export const useStickyNav = ({ |
| 15 | + initialDirection = ScrollDirection.DOWN, |
| 16 | + thresholdPixels, |
| 17 | + stickyRef, |
| 18 | +}: UseStickyNavProps) => { |
| 19 | + const [scrollDirection, setScrollDirection] = React.useState<ScrollDirection>( |
| 20 | + initialDirection |
| 21 | + ); |
| 22 | + const [isSticky, setSticky] = React.useState(false); |
| 23 | + |
| 24 | + React.useEffect(() => { |
| 25 | + const threshold = thresholdPixels ?? 0; |
| 26 | + |
| 27 | + let lastScrollPositon = 0; |
| 28 | + let ticking = false; |
| 29 | + |
| 30 | + const updateScrollDirection = () => { |
| 31 | + if (Math.abs(window.pageYOffset - lastScrollPositon) < threshold) { |
| 32 | + ticking = false; |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + setScrollDirection( |
| 37 | + window.pageYOffset > lastScrollPositon ? ScrollDirection.DOWN : ScrollDirection.UP |
| 38 | + ); |
| 39 | + |
| 40 | + setSticky( |
| 41 | + stickyRef.current && |
| 42 | + window.pageYOffset > stickyRef.current.getBoundingClientRect().top |
| 43 | + ? true |
| 44 | + : false |
| 45 | + ); |
| 46 | + |
| 47 | + lastScrollPositon = window.pageYOffset > 0 ? window.pageYOffset : 0; |
| 48 | + ticking = false; |
| 49 | + }; |
| 50 | + |
| 51 | + const handleScroll = () => { |
| 52 | + if (!ticking) { |
| 53 | + window.requestAnimationFrame(updateScrollDirection); |
| 54 | + ticking = true; |
| 55 | + } |
| 56 | + }; |
| 57 | + |
| 58 | + window.addEventListener('scroll', handleScroll); |
| 59 | + |
| 60 | + return () => { |
| 61 | + window.removeEventListener('scroll', handleScroll); |
| 62 | + }; |
| 63 | + }, [initialDirection, thresholdPixels, stickyRef]); |
| 64 | + |
| 65 | + return scrollDirection === ScrollDirection.UP && isSticky; |
| 66 | +}; |
0 commit comments