UNPKG

@jk-core/hooks

Version:
3 lines (2 loc) 2.15 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react"),a=({target:e,parent:r,callback:o,options:n})=>{c.useEffect(()=>{const t=e.current,s=r==null?void 0:r.current;if(!t)return()=>{};const u=new IntersectionObserver(([i])=>{i.isIntersecting&&o()},{...s?{root:s}:{},threshold:1,...n});return u.observe(t),()=>{u.unobserve(t)}},[o,n,r,e])},d=({targetRef:e,eventList:r=[],handler:o=()=>{}})=>{c.useEffect(()=>{const n=t=>{e.current&&!e.current.contains(t.target)&&o()};return Array.isArray(r)&&r.map(t=>window.addEventListener(t,n)),()=>{Array.isArray(r)&&r.map(t=>window.removeEventListener(t,n))}},[e,o,r])},w=e=>{const[r,o]=c.useState(()=>window.matchMedia(`(max-width: ${e}px)`).matches),n=c.useRef(null);return c.useEffect(()=>{const t=window.matchMedia(`(max-width: ${e}px)`);n.current=t;function s(){o(window.matchMedia(`(max-width: ${e}px)`).matches)}return n.current.addEventListener("change",s),()=>{var u;(u=n.current)==null||u.removeEventListener("change",s)}},[e]),r},h=()=>{const{history:e}=window;return{push:n=>{const t=new URL(window.location.href),s=`${t.origin}${t.pathname}${t.search}${t.hash}/${n}`;e.pushState({},"",s)},back:()=>{e.back()}}},f=e=>{c.useEffect(()=>{const r=()=>{const t="POP",{location:s}=window;e({action:t,location:s})},o=()=>{const t="PUSH",{location:s}=window;e({action:t,location:s})},n=()=>{const t="REPLACE",{location:s}=window;e({action:t,location:s})};return window.addEventListener("popstate",r),window.addEventListener("pushstate",o),window.addEventListener("replacestate",n),()=>{window.removeEventListener("popstate",r),window.removeEventListener("pushstate",o),window.removeEventListener("replacestate",n)}},[e])},m=(e,r)=>{const o=c.useRef(e),n=c.useRef(null);return c.useEffect(()=>(o.current=e,()=>{n.current!==null&&clearTimeout(n.current)}),[e]),c.useCallback((...s)=>{n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{o.current(...s)},r)},[r])};exports.useDebounce=m;exports.useHistory=h;exports.useHistoryEvent=f;exports.useInterectOutside=d;exports.useIntersectionObserver=a;exports.useMediaQuery=w; //# sourceMappingURL=index.cjs.map