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