UNPKG

portalis-component

Version:

Component Library for Nuxt 3 using TailwindCSS

23 lines (22 loc) 589 B
import { clamp } from "lodash-es"; import { focusable } from "tabbable"; export function useFocus(target, loop = true) { function travel(step) { const elements = focusable(target.value); const index = elements.indexOf(document.activeElement); const nextIndex = loop ? (index + step) % elements.length : clamp(index + step, 0, elements.length - 1); const targetFocus = elements.at(nextIndex); if (targetFocus !== void 0) targetFocus.focus(); } function next() { travel(1); } function prev() { travel(-1); } return { next, prev }; }