UNPKG

@konstructio/ui

Version:

A set of reusable and customizable React components built for konstruct.io

51 lines (50 loc) 1.46 kB
import { useRef as g, useEffect as a } from "react"; import { useDropdownContext as k } from "../contexts/dropdown.hook.js"; const A = ({ searchable: o, ulRef: n, wrapperInputRef: e, filteredOptions: f }) => { const r = g(0), { isOpen: s } = k(); a(() => { const m = n.current?.querySelectorAll("li") ?? [], t = Array.from(m).filter( (c) => c.getAttribute("data-action") !== "true" ), u = new AbortController(), i = () => { r.current < t.length - 1 ? (r.current = r.current + 1, t[r.current].focus()) : (r.current = 0, t[0].focus()); }, l = () => { r.current > 0 ? (r.current = r.current - 1, t[r.current].focus()) : (r.current = 0, e?.current && o ? e.current.querySelector("input")?.focus() : e.current?.focus()); }; return n.current?.addEventListener( "keydown", (c) => { switch (c.preventDefault(), c.key) { case "ArrowDown": { i(); break; } case "Tab": { c.shiftKey ? l() : i(); break; } case "ArrowUp": { r.current === 0 ? e.current?.focus() : l(); break; } case "Enter": { t[r.current]?.click(); break; } } }, { signal: u.signal } ), () => { u.abort(); }; }, [n, r, e, o, f.length]), a(() => { s || (r.current = 0); }, [s]); }; export { A as useNavigationUlList };