UNPKG

vuestic-ui

Version:
76 lines (75 loc) 2.43 kB
import { u as useAppGlobal } from "./useAppGlobal.js"; import { u as useDocument } from "./useDocument.js"; import { u as useWindow } from "./useWindow.js"; const FOCUSABLE_ELEMENTS_SELECTOR = ":where(a, button, input, textarea, select):not([disabled]), *[tabindex]"; const useTrapFocus = () => { const document = useDocument(); const window = useWindow(); const trapInEl = useAppGlobal("trapInEl", null); let focusableElements = []; let firstFocusableElement = null; let lastFocusableElement = null; const isFocusIn = (evt) => { var _a; return ((_a = trapInEl.value) == null ? void 0 : _a.contains(evt.target)) || false; }; const focusFirstElement = () => { firstFocusableElement == null ? void 0 : firstFocusableElement.focus(); }; const focusLastElement = () => { lastFocusableElement == null ? void 0 : lastFocusableElement.focus(); }; const onKeydown = (evt) => { var _a, _b; const isTabPressed = evt.code === "Tab"; const isShiftPressed = evt.shiftKey; if (!isTabPressed) { return; } if (!isFocusIn(evt)) { evt.preventDefault(); isShiftPressed ? focusLastElement() : focusFirstElement(); return; } if (((_a = document.value) == null ? void 0 : _a.activeElement) === lastFocusableElement && !isShiftPressed) { evt.preventDefault(); focusFirstElement(); return; } if (((_b = document.value) == null ? void 0 : _b.activeElement) === firstFocusableElement && isShiftPressed) { evt.preventDefault(); focusLastElement(); } }; const trapFocusIn = (el) => { trapInEl.value = el; freeFocus(); trapFocus(); }; const trapFocus = () => { var _a; if (!trapInEl.value) { return; } focusableElements = Array.from(trapInEl.value.querySelectorAll(FOCUSABLE_ELEMENTS_SELECTOR)); firstFocusableElement = focusableElements[0]; lastFocusableElement = focusableElements[focusableElements.length - 1]; (_a = window.value) == null ? void 0 : _a.addEventListener("keydown", onKeydown); }; const freeFocus = () => { var _a; focusableElements = []; firstFocusableElement = null; lastFocusableElement = null; (_a = window.value) == null ? void 0 : _a.removeEventListener("keydown", onKeydown); }; return { trapFocus, freeFocus, trapFocusIn }; }; export { useTrapFocus as u }; //# sourceMappingURL=useTrapFocus.js.map