@konstructio/ui
Version:
A set of reusable and customizable React components built for konstruct.io
59 lines (58 loc) • 1.65 kB
JavaScript
import { useEffect as l, useRef as b } from "react";
var k = ({ ulRef: t, inputRef: c, wrapperRef: u, options: a }) => {
const r = b(0);
l(() => {
const e = t.current?.querySelectorAll("li") ?? [], n = new AbortController(), o = () => {
r.current < e.length - 1 ? (r.current = r.current + 1, e[r.current].focus()) : (r.current = 0, e[0].focus());
}, i = () => {
r.current > 0 ? (r.current = r.current - 1, e[r.current].focus()) : (r.current = 0, c.current?.focus());
};
return t.current?.addEventListener("keydown", (s) => {
switch (s.preventDefault(), s.key) {
case "ArrowDown":
o();
break;
case "Tab":
s.shiftKey ? i() : o();
break;
case "ArrowUp":
r.current === 0 ? c.current?.focus() : i();
break;
case "Enter":
e[r.current].querySelector("button")?.click();
break;
}
}, { signal: n.signal }), () => {
n.abort();
};
}, [
c,
t,
a,
r
]), l(() => {
const e = new AbortController();
return c.current?.addEventListener("keydown", (n) => {
if (n.key === "ArrowDown") {
const o = t.current?.querySelector("li");
o && o.focus();
}
}, { signal: e.signal }), () => {
e.abort();
};
}, [
c,
t,
a
]), l(() => {
const e = new AbortController();
return u.current?.addEventListener("mouseenter", () => {
(t.current?.querySelectorAll("li") ?? []).forEach((n) => n.blur());
}, { signal: e.signal }), () => {
e.abort();
};
}, [t, u]);
};
export {
k as useNavigationUlList
};