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