File size: 1,852 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
import { SpringValue, useSpring } from '@react-spring/web'
import { useIsomorphicLayoutEffect } from './useIsomorphicEffect'
import { useStickyHeader } from './useStickyHeader'
import { useWindowScrolling, SCROLL_DIR } from './useWindowScrolling'
interface UseAnimatedHeaderProps {
isHeader?: boolean
alwaysAnimate?: boolean
heights: [desktop: number, mobile: number]
}
export const useAnimatedHeader = ({
isHeader = true,
alwaysAnimate = false,
heights,
}: UseAnimatedHeaderProps): [
styles: { top: SpringValue<number> },
isStuck: boolean,
scrollTop: number,
direction: SCROLL_DIR | undefined,
] => {
const [direction, scrollTop] = useWindowScrolling({
active: true,
threshold: [0, 20],
})
const isStuck = useStickyHeader(heights)
const [styles, api] = useSpring(() => ({
top: 0,
y: 0,
}))
/**
* Handles forcing the main nav to
* drop back down when scrolling up.
* Handles _not_ showing the main nav
* if a subnav link is clicked to scroll
* back up.
*/
useIsomorphicLayoutEffect(() => {
const { innerWidth } = window
const limit = innerWidth < 768 ? heights[1] : heights[0]
if (direction === 'down') {
if (!isStuck) {
api.set({
top: isHeader ? limit * -1 : 0,
})
}
if (alwaysAnimate && !isStuck) {
api.start({
from: {
y: limit,
},
to: {
y: 0,
},
})
}
if (isStuck) {
api.start({
y: 0,
})
}
} else if (direction === 'up') {
if (scrollTop <= limit && !isStuck) {
api.set({
top: 0,
y: 0,
})
} else {
api.start({
y: limit,
})
}
}
}, [direction, isStuck])
return [styles, isStuck, scrollTop, direction]
}
|