UNPKG

@jk-core/hooks

Version:
108 lines (107 loc) 3.03 kB
import { useRef as i, useEffect as a, useCallback as d, useState as w } from "react"; const m = (e, n) => { const s = i(e), o = i(null); return a(() => (s.current = e, () => { o.current !== null && clearTimeout(o.current); }), [e]), d((...r) => { o.current && clearTimeout(o.current), o.current = setTimeout(() => { s.current(...r); }, n); }, [n]); }, f = () => { const { history: e } = window; return { push: (o) => { const t = new URL(window.location.href), r = `${t.origin}${t.pathname}${t.search}${t.hash}/${o}`; e.pushState({}, "", r); }, back: () => { e.back(); } }; }, p = (e) => { a(() => { const n = () => { const t = "POP", { location: r } = window; e({ action: t, location: r }); }, s = () => { const t = "PUSH", { location: r } = window; e({ action: t, location: r }); }, o = () => { const t = "REPLACE", { location: r } = window; e({ action: t, location: r }); }; return window.addEventListener("popstate", n), window.addEventListener("pushstate", s), window.addEventListener("replacestate", o), () => { window.removeEventListener("popstate", n), window.removeEventListener("pushstate", s), window.removeEventListener("replacestate", o); }; }, [e]); }, l = ({ targetRef: e, eventList: n = [], handler: s = () => { } }) => { a(() => { const o = (t) => { e.current && !e.current.contains(t.target) && s(); }; return Array.isArray(n) && n.map((t) => window.addEventListener(t, o)), () => { Array.isArray(n) && n.map((t) => window.removeEventListener(t, o)); }; }, [e, s, n]); }, v = ({ target: e, parent: n, callback: s, options: o }) => { a(() => { const t = e.current, r = n?.current; if (!t) return () => { }; const c = new IntersectionObserver(([u]) => { u.isIntersecting && s(); }, { ...r ? { root: r } : {}, threshold: 1, ...o }); return c.observe(t), () => { c.unobserve(t); }; }, [s, o, n, e]); }, E = (e) => { const n = typeof window < "u" && typeof window.matchMedia < "u", [s, o] = w(() => { if (!n) return !1; try { return window.matchMedia(`(max-width: ${e}px)`).matches; } catch { return !1; } }), t = i(null); return a(() => { if (n) try { const r = window.matchMedia(`(max-width: ${e}px)`); t.current = r; const c = () => { try { o(window.matchMedia(`(max-width: ${e}px)`).matches); } catch { } }; return r.addEventListener ? (r.addEventListener("change", c), () => { r.removeEventListener("change", c); }) : (r.addListener(c), () => { r.removeListener(c); }); } catch { } }, [n, e]), s; }; export { m as useDebounce, f as useHistory, p as useHistoryEvent, l as useInterectOutside, v as useIntersectionObserver, E as useMediaQuery }; //# sourceMappingURL=index.js.map