@indielayer/ui
Version:
Indielayer UI Components with Tailwind CSS build for Vue 3
53 lines (52 loc) • 1.8 kB
JavaScript
import { ref as F, onUnmounted as h, unref as w, nextTick as x, watch as E } from "vue";
const T = 'button:not([tabindex="-1"]), [href], input, select, textarea, li, a, [tabindex]:not([tabindex="-1"])';
function p() {
const l = F([]);
let r = null, a = null, f = null, s = null, o = null;
function d(e) {
return e ? e.$el ? e.$el : e : null;
}
function m(e) {
const n = d(e);
if (!n)
return;
const t = n.querySelectorAll(T);
l.value = Array.from(t), a = l.value[0] || null, f = l.value[l.value.length - 1] || null;
}
const v = (e) => {
if (e.key !== "Tab" || l.value.length === 0)
return;
const n = e.shiftKey, t = document.activeElement, u = a, c = f;
if (!t) {
e.preventDefault(), u == null || u.focus();
return;
}
!n && t === c ? (e.preventDefault(), u == null || u.focus()) : n && t === u && (e.preventDefault(), c == null || c.focus());
};
async function b(e, n) {
var c;
if (typeof window > "u" || (i(), s = document.activeElement, o = w(e), !o))
return;
await x(), m(o);
const t = (n == null ? void 0 : n.initialFocusIndex) ?? 0;
(c = l.value[t]) == null || c.focus(), document.addEventListener("keydown", v), r = new MutationObserver(() => m(o));
const u = d(o);
u && r.observe(u, { childList: !0, subtree: !0 }), typeof e == "object" && e !== null && "value" in e && E(e, (y) => {
i(), y !== null && b(e, n);
});
}
function i(e) {
document.removeEventListener("keydown", v), r == null || r.disconnect(), r = null, e != null && e.returnFocus && s && s.focus(), o = null;
}
return h(() => {
i({ returnFocus: !0 });
}), {
initFocusTrap: b,
clearFocusTrap: i,
focusable: l
// expose for advanced use
};
}
export {
p as useFocusTrap
};