UNPKG

@dnanpm/styleguide

Version:

DNA Styleguide repository provides the set of components and theme object used in various DNA projects.

67 lines (64 loc) 1.73 kB
import { useRef, useEffect } from 'react'; const isBrowser = typeof window !== 'undefined'; const getScrollPosition = (ref) => { const { element } = ref; const { useWindow } = ref; if (!isBrowser) { return { x: 0, y: 0, }; } const target = element ? element.current : document.body; const position = target.getBoundingClientRect(); return useWindow ? { x: window.scrollX, y: window.scrollY, } : { x: position.left, y: position.top, }; }; const useScrollPosition = (effect, element, useWindow, wait) => { const position = useRef(getScrollPosition({ useWindow, })); const throttleTimeout = useRef(null); const callBack = () => { const currPos = getScrollPosition({ element, useWindow, }); effect({ prevPos: position.current, currPos, }); position.current = currPos; throttleTimeout.current = null; }; useEffect(() => { if (!isBrowser) { return undefined; } const handleScroll = () => { if (wait) { if (throttleTimeout.current === null) { throttleTimeout.current = setTimeout(callBack, wait); } } else { callBack(); } }; window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }); }; useScrollPosition.defaultProps = { element: false, useWindow: false, wait: null, }; export { useScrollPosition as default };