UNPKG

@n8tb1t/use-scroll-position

Version:
2 lines 1.05 kB
import{useCallback as p,useRef as d}from"react";var n=typeof window<"u";import{useEffect as g,useLayoutEffect as L}from"react";var u=n?L:g;var x={x:0,y:0},E=o=>o?.getBoundingClientRect(),P=({useWindow:o,target:f,root:i})=>{if(!n)return x;if(o)return{x:window.scrollX,y:window.scrollY};let t=E(i?.current),e=E(f?.current||document.body);return e?t?{x:(t.x||0)-(e.x||0),y:(t.y||0)-(e.y||0)}:{x:e.left,y:e.top}:x};var S=(o,f,i,t,e,r)=>{let a=d({x:0,y:0}),s=d(void 0),y=d(o);y.current=o;let c=p(()=>{let R=P({useWindow:t,root:r,target:i});y.current({prevPos:a.current,currPos:R}),a.current=R},[t,r,i]),m=p(()=>{c(),s.current=void 0},[c]),l=p(()=>{e?s.current===void 0&&(s.current=setTimeout(m,e)):m()},[m,e]);u(()=>{c()},[c]),u(()=>{if(n)return r?.current?r.current.addEventListener("scroll",l,{passive:!0}):window.addEventListener("scroll",l,{passive:!0}),()=>{r?r.current?.removeEventListener("scroll",l):window.removeEventListener("scroll",l),s.current&&clearTimeout(s.current)}},f)};export{S as useScrollPosition}; //# sourceMappingURL=index.js.map