UNPKG

@flexilla/utilities

Version:

Utilities package for flexilla library

49 lines (48 loc) 1.53 kB
import { $getEl as m, $$ as w } from "./selector.js"; const A = ({ containerElement: b, targetChildren: a = "a:not([disabled]), button:not([disabled])", direction: n }) => { let s = !1; const l = m(b) || document.body, t = typeof a == "string" ? w(a, l) : a, f = (r) => { if (r.preventDefault(), l.focus(), t.length === 0) return; const c = r.key, u = document.activeElement; let e = t.findIndex((o) => o === u); if (e === -1) { c === "ArrowUp" || c === "ArrowLeft" ? t[t.length - 1].focus() : t[0].focus(); return; } const i = (o) => o > 0 ? o - 1 : t.length - 1, d = (o) => o < t.length - 1 ? o + 1 : 0, p = n === "all" || n === "up-down", k = n === "all" || n === "left-right"; switch (c) { case "ArrowDown": p && (r.preventDefault(), e = d(e)); break; case "ArrowRight": k && (r.preventDefault(), e = d(e)); break; case "ArrowUp": p && (r.preventDefault(), e = i(e)); break; case "ArrowLeft": k && (r.preventDefault(), e = i(e)); break; case "Home": r.preventDefault(), e = 0; break; case "End": r.preventDefault(), e = t.length - 1; break; default: return; } t[e] !== u && t[e].focus(); }; return { make: () => { s || (document.addEventListener("keydown", f), s = !0); }, destroy: () => { s && (document.removeEventListener("keydown", f), s = !1); } }; }; export { A as keyboardNavigation };