@konstructio/ui
Version:
A set of reusable and customizable React components built for konstruct.io
63 lines (62 loc) • 2.21 kB
JavaScript
import "../constants/index.js";
import { useCallback as D, useEffect as c, useMemo as v, useRef as w, useState as E } from "react";
var H = ({ canResize: n = !1, defaultWidth: I = 500, isOpen: s, maxWidth: u = 800, minWidth: l = 400, position: t = "right", onClose: M }) => {
const [T, g] = E(!1), [a, h] = E(!1), [L, f] = E(I), d = w(!1), i = w(() => {
}), m = w(() => {
});
c(() => {
let e;
return s ? (g(!0), e = setTimeout(() => h(!0), 10)) : (h(!1), e = setTimeout(() => g(!1), 300)), () => {
clearTimeout(e);
};
}, [s]), c(() => {
if (!s) return;
const e = new AbortController(), r = (A) => {
A.code === "Escape" && M?.();
};
return window.addEventListener("keydown", r, { signal: e.signal }), () => {
e.abort();
};
}, [s, M]);
const o = D(() => {
document.removeEventListener("mousemove", i.current), document.removeEventListener("mouseup", m.current), document.body.style.cursor = "", document.body.style.userSelect = "";
}, []);
c(() => {
i.current = (e) => {
if (!d.current || !n) return;
let r;
t === "right" ? r = window.innerWidth - e.clientX : r = e.clientX, r = Math.max(l, Math.min(u, r)), f(r);
}, m.current = () => {
d.current = !1, o();
};
}, [
t,
l,
u,
n,
o
]);
const _ = D(() => {
d.current = !0, document.addEventListener("mousemove", i.current), document.addEventListener("mouseup", m.current), document.body.style.cursor = "col-resize", document.body.style.userSelect = "none";
}, []), b = D((e) => {
if (!n) return;
const r = t === "right" && e.key === "ArrowLeft" || t === "left" && e.key === "ArrowRight", A = t === "right" && e.key === "ArrowRight" || t === "left" && e.key === "ArrowLeft";
r ? (e.preventDefault(), f((y) => Math.min(u, y + 20))) : A && (e.preventDefault(), f((y) => Math.max(l, y - 20)));
}, [
n,
t,
u,
l
]);
return c(() => o, [o]), {
isAnimating: a,
isVisible: T,
width: L,
translateClass: v(() => a ? "translate-x-0" : t === "left" ? "-translate-x-full" : "translate-x-full", [a, t]),
handleMouseDown: _,
handleKeyDown: b
};
};
export {
H as useDrawer
};