@frontify/fondue
Version:
Design system of Frontify
33 lines (32 loc) • 1.09 kB
JavaScript
import { useState as a, useCallback as k, useEffect as c } from "react";
const E = (r, i, f = "li > button:not(:disabled)") => {
const [s, n] = a(0), [o, l] = a(), [h, u] = a(""), y = k(
(t) => {
if (!o || !["Tab", "ArrowDown", "ArrowUp", "Escape"].includes(t.key))
return;
const e = t.key === "Tab" && !t.shiftKey, b = t.key === "Tab" && t.shiftKey, d = t.key === "Escape", m = e || t.key === "ArrowDown", w = b || t.key === "ArrowUp";
if (b && s <= 0 || e && s >= o.length - 1 || d) {
u("CLOSE_MENU");
return;
}
m ? n(Math.min(s + 1, o.length - 1)) : w && n(Math.max(s - 1, 0)), t.preventDefault();
},
[o, s]
);
return c(() => {
if (!r || !i)
return;
const t = i.querySelectorAll(f);
for (const e of t)
e.onkeydown = y;
!o && t.length > 0 && l(t);
}, [r, i, o, y, f]), c(() => {
o && o[s] && o[s].focus();
}, [s, o]), c(() => {
r || (l(void 0), u("")), n(0);
}, [r]), h;
};
export {
E as useMenuKeyboardNavigation
};
//# sourceMappingURL=useMenuKeyboardNavigation.es.js.map